# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# #递归方法
# def isSymmetric(self, root: TreeNode) -> bool:
# if not root:
# return True
# else:
# return self.isSym(root.left, root.right)
# def isSym(self, p, q):
# if not p and not q:
# return True
# elif not p or not q:
# return False
# elif p.val == q.val:
# return self.isSym(p.left, q.right) and self.isSym(p.right, q.left)
# else:
# return False
#非递归方法
def isSymmetric(self, root: TreeNode) -> bool:
#建立两个队列,分别代表根节点的left , right
if not root:
return True
#两个队列
q1, q2 = [], []
#储存每层的节点值
ret1, ret2 = [], []
#从第二层节点开始,比较每层节点左右是否为镜像
if root.left:
q1 = [root.left]
ret1 = [root.left.val]
if root.right:
q2 = [root.right]
ret2 = [root.right.val]
while q1 or q2:
if not q1 or not q2:
return False
#当前层左右两边是否相等,相等为镜像
elif ret1 == ret2:
ret1, ret2 = [], []
if len(q1) != len(q2):
return False
for i in range(len(q1)):
node1 = q1.pop(0)
#先左后右遍历
if node1.left:
q1.append(node1.left)
ret1.append(node1.left.val)
else:ret1.append(None) #防止值相等, 但顺序对应不上(非镜像)
if node1.right:
q1.append(node1.right)
ret1.append(node1.right.val)
else:ret1.append(None)
node2 = q2.pop(0)
#先右后左遍历
if node2.right:
q2.append(node2.right)
ret2.append(node2.right.val)
else:ret2.append(None)
if node2.left:
q2.append(node2.left)
ret2.append(node2.left.val)
else:ret2.append(None)
else:
return False
return True