1 """
2 Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
3 For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
4 1
5 / \
6 2 2
7 / \ / \
8 3 4 4 3
9 But the following [1,2,2,null,3,null,3] is not:
10 1
11 / \
12 2 2
13 \ \
14 3 3
15 """
16 class TreeNode:
17 def __init__(self, x):
18 self.val = x
19 self.left = None
20 self.right = None
21 class Solution1(object):
22 def isSymmetric(self, root):
23 if root == None: #空树的情况
24 return True
25 else:
26 return self.isSym(root.left, root.right) #递归函数
27 def isSym(self, L, R): #L左子树,R右子树
28 if L == None and R == None: #只有根节点的情况
29 return True
30 elif L == None or R == None:
31 return False
32 elif L.val == R.val:
33 return self.isSym(L.left, R.right) and self.isSym(L.right, R.left)
34 #!!!递归调用,注意是两个相等的值,左子树的左孩子和右子树的右孩子
35 else:
36 return False
37
38 """
39 把问题分解为第二层的两个子树为对称的,
40 可以近似地判断两个二叉树是否相同;
41 """
42
43 """
44 用层次遍历BFS的方法,判断每一层结点的val是否对称
45 !!! val[::-1] == val ,判断对称一条语句就可以实现
46 层次遍历用队列存储
47 """
48 class Solution2(object):
49 def isSymmetric(self, root):
50 if root == None: #空树的情况
51 return True
52 queue = [root] #先将根结点加入队列
53 while queue:
54 value = [x.val if x else None for x in queue] #将队列的有效值放入value
55 if value[::-1] != value: #!!!判断是否对称。切片方法
56 return False #切片格式[第一个元素编号:第二个元素编号加一:步长]
57 newqueue = [] #新队列用来存储下一层
58 for x in queue: #层次遍历入队操作
59 if x:
60 newqueue.append(x.left)
61 newqueue.append(x.right)
62 queue = newqueue #覆盖原来队列循环判断下一层
63 return True