題目
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3]
is symmetric:
1 / \ 2 2 / \ / \ 3 4 4 3
But the following [1,2,2,null,3,null,3]
is not:
1 / \ 2 2 \ \ 3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
中文題意:給定一棵二叉樹,判斷其是否關於中心軸線對稱。
分析
解答
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if(root==NULL)
return true;
if(root->left==NULL && root->right==NULL)
return true;
if(root->left==NULL || root->right==NULL)
return false;
return isMirrorTree(root->left,root->right);
}
bool isMirrorTree(TreeNode *p, TreeNode *q){
if(p==NULL && q==NULL)
return true;
if(p==NULL || q==NULL)
return false;
if(p->val!=q->val)
return false;
if((p->left==NULL && p->right==NULL) && (q->left==NULL && q->right==NULL)){
if(p->val==q->val)
return true;
}
return (isMirrorTree(p->left,q->right) && (isMirrorTree(p->right,q->left)));
}
};
時間複雜度爲O(n)。