题目:Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1 / \ 2 2 / \ / \ 3 4 4 3
But the following is not:
1 / \ 2 2 \ \ 3 3
解题思路:(1)如果一个树是对称的,那么左子树和右子树的关系是对称的,把左子树进行翻转就可以得到和右子树相同的树,比如把左子树进行翻转
2 2 / \ 得到 / \ 3 4 4 3然后和右子树作对比,如果相同,则说明这棵树是对称树。否则不是。
(2)上述想法需要首先将根节点的左子树或者右子树进行翻转,然后再判断。然而对称树的左子树和右子树是对称的,根据这个规律可以直接判断左右子树是否对称。不需要先翻转,在判断相等。
/**
* 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) return true;
if(!root->left && !root->right) return true;
MirrorRecursively(root->left);<span style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;">//翻转根节点的左子树</span>
return isEqualTree(root->left,root->right);
}
void MirrorRecursively(TreeNode* root){
if(!root) return;
if(!root->left && !root->right) return;
TreeNode *temp = root->left;
root->left = root->right;
root->right = temp;
MirrorRecursively(root->left);
MirrorRecursively(root->right);
}
bool isEqualTree(TreeNode *p, TreeNode *q){
if(!p) return !q;
if(!q) return !p;
if(p->val == q->val)
return isEqualTree(p->left,q->left) && isEqualTree(p->right,q->right);
return false;
}
};
想法二:
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if(!root) return true;
if(!root->left && !root->right) return true;
return isEqualTree(root->left,root->right);
}
bool isEqualTree(TreeNode *p, TreeNode *q){
if(!p) return !q;
if(!q) return !p;
if(p->val == q->val)
return isEqualTree(p->left,q->right) && isEqualTree(p->right,q->left);
return false;
}
};
用循环实现:
class Solution {
public:
bool isSymmetric(TreeNode* root) {
stack<TreeNode *>left;//遇见相同的加入,并在合适的时候弹出
stack<TreeNode *>right;//
TreeNode *l =root;
TreeNode *r =root;
while(1){
if(!l && !r){
if(left.empty()&&right.empty()) return true;
else{
l = left.top()->right;
r = right.top()->left;
left.pop();
right.pop();
}
}
else if (!l && r || !r&&l) return false;
else if(l->val!=r->val) return false;
else{
left.push(l);
right.push(r);
l = l->left;
r = r->right;
}
}
}
};