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
思路:对比root左子树右子树的存在情况,以及root->left->left == root->right->right &&root->left->right ==root->right->left
代码
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if(!root)return true;
return isSame(root->left,root->right);
}
bool isSame(TreeNode* r1,TreeNode* r2){
if(!r1&&!r2){
return true;
}
if(!r1||!r2||r1->val!=r2->val)return false;
return isSame(r1->right,r2->left)&&isSame(r1->left,r2->right);
}
};