Symmetric Tree

来源:互联网 发布:会计记账软件 编辑:程序博客网 时间:2024/06/07 14:40


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.

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    bool isSymmetric(TreeNode *root) {        return isSymmetric(root,root);    }private:    bool isSymmetric(TreeNode *p,TreeNode *q){        if(!p && !q) return true;        if(p && q){            if(p->val==q->val){                bool lhs = isSymmetric(p->left,q->right);                bool rhs = isSymmetric(p->right,q->left);                return lhs && rhs;            }else{                return false;            }        }else{            return false;        }    }};

0 0
原创粉丝点击