Symmetric Tree

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

 

Note:
Bonus points if you could solve it both recursively and iteratively.

class Solution {
public:
    bool isSameTree(TreeNode *p, TreeNode *q) {
        if (!p && !q){
            return true;
        }
        if (!p && q || !q && p){
            return false;
        }
        return isSameTree(p->left,q->left) && isSameTree(p->right,q->right) && p->val == q->val;
    }
    void build(TreeNode * root,TreeNode *& newroot){
        if (!root){
            return;
        }
        if (!newroot){
            newroot = new TreeNode(root->val);
            build(root->left,newroot->right);
            build(root->right,newroot->left);
        }
    }    
    bool isSymmetric(TreeNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (!root){
            return true;
        }
        TreeNode * newroot = NULL;
        build(root,newroot);
        return isSameTree(root,newroot);
    }
};

 

posted @ 2013-07-02 00:54  一只会思考的猪  阅读(138)  评论(0编辑  收藏  举报