[leetcode] 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

分析:
题目是要判断左右两颗子树是否对称,采用只要根节点的值相同,并且左边子树的左子树和右边子树饿右子树对称 且 左边子树的右子树和右边子树的左子树对称。采用树的遍历的思想,递归的解决该问题。
代码:

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;
    }
};

你可能感兴趣的:(LeetCode,二叉树,遍历)