原題地址:https://oj.leetcode.com/problems/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
解題思路:這題也不難。需要用一個help函數,當然也是遞歸的。當存在左右子樹時,判斷左右子樹的根節點值是否相等,如果想等繼續遞歸判斷左子樹根的右子樹根節點和右子樹根的左子樹根節點以及左子樹根的左子樹根節點和右子樹根的右子樹根節點的值是否相等。然后一直遞歸判斷下去就可以了。
代碼:
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param root, a tree node # @return a boolean def help(self, p, q): if p == None and q == None: return True if p and q and p.val == q.val: return self.help(p.right, q.left) and self.help(p.left, q.right) return False def isSymmetric(self, root): if root: return self.help(root.left, root.right) return True