16.Symmetric Tree
题目描述:
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
判断一棵树是否对称,只需要考虑对称时的条件以及非对称时的条件(例如树的第三层),然后递归检测
代码如下
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if(!root) return true;
return helper(root->left, root->right);
}
bool helper(TreeNode* p, TreeNode* q){
if(!p && !q) return true;
else if(!p || !q) return false;
if(p->val != q->val) return false;
return helper(p->left,q->right) && helper(p->right, q->left);
}
};