1. 程式人生 > >LeetCode 101. Symmetric Tree (對稱樹)

LeetCode 101. Symmetric Tree (對稱樹)

原題

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

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

But the following [1,2,2,null,3,null,3] is not:

    1
   / \
  2   2
   \   \
   3    3

Reference Answer

思路分析

看一棵二叉樹是否對稱,就要首先看根節點的左右節點A和B是否有相同的值,如果A和B的值相等,那麼要繼續判斷A的左節點和B的右節點以及A的右節點和B的左節點是否對稱,通過這樣的方式來遞迴得到結果。

Reference Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution: def isSymmetric(self, root): """ :type root: TreeNode :rtype: bool """ if not root: return True return self.backtracking(root.left, root.right) def backtracking(self, lchild, rchild): if not lchild and
not rchild: return True if not lchild or not rchild: return False if lchild.val == rchild.val: return self.backtracking(lchild.left, rchild.right) and self.backtracking(lchild.right, rchild.left) else: return False

C++ 版本

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isSymmetric(TreeNode* root) {
        if (!root){
            return true;
        }
        return backTracking(root->left, root->right);
    }
    
    bool backTracking(TreeNode* lchild, TreeNode* rchild){
        if (!lchild && !rchild){
            return true;
        }
        if (!lchild || !rchild){
            return false;
        }
        if (lchild->val == rchild->val){
            return backTracking(lchild->left, rchild->right) && backTracking(lchild->right, rchild->left);
        }
        else{
            return false;
        }
    }
};