LeetCode101--对称二叉树
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 if p 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 return isSameTree(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)