[LeetCode]Symmetric Tree

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
Note:
Bonus points if you could solve it both recursively and iteratively.

我们要检查树每层的节点是否都关于中间轴对称,所以可以通过迭代检查。
代码如下:

class Solution {
public:    
    bool isSymmetric(TreeNode* root) {
        if(!root) return true;     
        return check(root->left,root->right);
    }
    bool check(TreeNode *l, TreeNode *r){
        if(!l && !r){
            return true;
        }
        else if(!l || !r){
            return false;
        }
        if(l->val != r->val){
            return false;
        }
        return check(l->left,r->right) && check(l->right,r->left);
    }
};
posted @ 2017-10-24 12:48  liangf27  阅读(63)  评论(0编辑  收藏  举报