2叉树

来源:互联网 发布:python enumerate 编辑:程序博客网 时间:2024/06/07 22:32

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
分析:
题目是要判断左右两颗子树是否对称,采用只要根节点的值相同,并且左边子树的左子树和右边子树饿右子树对称 且 左边子树的右子树和右边子树的左子树对称。采用树的遍历的思想,递归的解决该问题。
转载于:http://blog.csdn.net/pwiling/article/details/50868313

这里写代码片class Solution {public:    bool isSymmetric(TreeNode* root) {        if(root==NULL||(root->left==NULL&&root->right==NULL))            return true;        return postorder(root->left,root->right);    }    bool postorder(TreeNode* p,TreeNode* q)    {        if(p&&q)        {            if(p->val!=q->val)                return false;            return postorder(p->left,q->right)&&postorder(p->right,q->left);        }else if(p==NULL&&q==NULL)            return true;        else            return false;    }};
2 0
原创粉丝点击