LeetCode101--對稱二叉樹
阿新 • • 發佈:2018-12-03
1 ''' 2 給定一個二叉樹,檢查它是否是映象對稱的。 3 ''' 4 5 6 class TreeNode: 7 def __init__(self, x): 8 self.val = x 9 self.left = None 10 self.right = None 11 12 13 class Solution: 14 def isSymmetric(self, root): 15 """ 16 :type root: TreeNode 17:rtype: bool 18 """ 19 if not root: 20 return True 21 else: 22 # p=root.left;q=root.right 23 def isSameTree(p, q): 24 if not p and not q: # 兩二叉樹皆為空,遞迴邊界,兩者皆為空返回真 25 return True 26 ifp and q and p.val == q.val: 27 l = isSameTree(p.left, q.right) 28 r = isSameTree(p.right, q.left) 29 return l and r # 需要l與r皆為true時,才返回真。只用最後一次遞迴邊界return值 30 else: 31 return False 32 33 returnisSameTree(root.left, root.right) 34 35 36 if __name__ == '__main__': 37 n = [1, 2, 2, 3, 4, 4, 3] 38 root = TreeNode(1) 39 l1 = root.left = TreeNode(2) 40 r1 = root.right = TreeNode(2) 41 l2ll = l1.left = TreeNode(3) 42 l2lr = l1.right = TreeNode(4) 43 l2rl = r1.left = TreeNode(4) 44 l2rr = r1.right = TreeNode(3) 45 ret = Solution().isSymmetric(root) 46 print(ret)