[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;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章