题目描述: 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
思路:题目的要求为判断一棵树是否对称, 可以从根节点向下,将二叉树看成两颗树, 判断这两棵树是否对称。采用递归的方式,代码如下:
1 # Definition for a binary tree node. 2 # class TreeNode(object): 3 # def __init__(self, x): 4 # self.val = x 5 # self.left = None 6 # self.right = None 7 8 class Solution(object): 9 def isSymmetric(self, root): 10 """ 11 :type root: TreeNode 12 :rtype: bool 13 """ 14 nums = [] 15 st = [] 16 if not root: 17 return True 18 return self.helper(root.left, root.right) 19 20 def helper(self, left, right): 21 if not left and not right: 22 return True 23 elif not left or not right: 24 return False 25 if left.val != right.val: 26 return False 27 return self.helper(left.left, right.right) and self.helper(left.right, right.left)
# Definition for a binary tree node.# class TreeNode(object):# def __init__(self, x):# self.val = x# self.left = None# self.right = None
class Solution(object): def isSymmetric(self, root): """ :type root: TreeNode :rtype: bool """ nums = [] st = [] if not root: return True return self.helper(root.left, root.right) def helper(self, left, right): if not left and not right: return True elif not left or not right: return False if left.val != right.val: return False return self.helper(left.left, right.right) and self.helper(left.right, right.left)