1. 程式人生 > >Leetcode:101.對稱二叉樹

Leetcode:101.對稱二叉樹

給定一個二叉樹,檢查它是否是映象對稱的。

例如,二叉樹 [1,2,2,3,4,4,3] 是對稱的。

    1
   / \
  2   2
 / \ / \
3  4 4  3

但是下面這個 [1,2,2,null,3,null,3] 則不是映象對稱的:

    1
   / \
  2   2
   \   \
   3    3

解題思路:

非遞迴方法:將根節點的左右子樹之一的所有節點旋轉,然後判斷左右子樹是否相等即可,判斷兩個子樹是否相等可以藉助Leetcode100題的程式碼。

                                  

C++程式碼
class Solution {
public:
    bool isSymmetric(TreeNode* root) {
        if (root == NULL || root->left == NULL&&root->right == NULL) return true;
        if (root->left == NULL || root->right == NULL) return false;
        if (root->left->val != root->right->val) return false;
        //旋轉root節點的右子樹
        Rotate(root->right);
        //判斷左右子樹是否相等
        return isSameTree(root->left, root->right);
    }
    void Rotate(TreeNode* root) {
        if (root == NULL) return;
        TreeNode* temp = root->left;
        root->left = root->right;
        root->right = temp;
        if (root->left != NULL) Rotate(root->left);
        if (root->right != NULL) Rotate(root->right);
    }
    bool isSameTree(TreeNode* p, TreeNode* q) {
        if (p == NULL&&q == NULL) return true;
        if (p == NULL || q == NULL) return false;
        queue<TreeNode*> Q1, Q2;
        Q1.push(p); Q2.push(q);
        while (!Q1.empty() && !Q2.empty() && Q1.size() == Q2.size()) {
            for (int i = 1; i <= int(Q1.size()); i++) {
                TreeNode *T1 = Q1.front(), *T2 = Q2.front();
                if (T1->val != T2->val) return false;
                if (!Same_Struct_TreeNode(T1, T2)) return false;
                Q1.pop(); Q2.pop();
                if (hasLChild(T1)) { Q1.push(T1->left); Q2.push(T2->left); }
                if (hasRChild(T1)) { Q1.push(T1->right); Q2.push(T2->right); }
            }
        }
        return true;
    }
};