def __init__(self, x):
self.val = x
self.left = None
self.right = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param pRoot TreeNode类
# @return bool布尔型
#
# 使用中序遍历,获取列表,考虑列表是否对称即可
# 层次遍历加中序遍历,保证对称
class Solution:
def isSymmetrical(self , pRoot: TreeNode) -> bool:
# write code here
if not pRoot:
return True
# 中序遍历部分
nodestack = []
reslist = []
pRoot2 = pRoot
while pRoot or len(nodestack) != 0:
while pRoot:
nodestack.append(pRoot)
pRoot = pRoot.left
pRoot = nodestack.pop()
reslist.append(pRoot.val)
pRoot = pRoot.right
res1 = self.isSymmetic(reslist)
# 层次遍历部分
nodeduilie = [pRoot2]
count = 1
while True:
tempcount = 0
tempreslist = []
for i in range(count):
tempnode = nodeduilie.pop(0)
tempreslist.append(tempnode.val)
if tempnode.left:
nodeduilie.append(tempnode.left)
tempcount += 1
if tempnode.right:
nodeduilie.append(tempnode.right)
tempcount += 1
# 不满足层次遍历也不行
if not self.isSymmetic(tempreslist):
return False
count = tempcount
if count == 0:
break
return res1
def isSymmetic(self, alist: [int]):
length = len(alist)
for i in range(length // 2):
if alist[i] != alist[length - i - 1]:
return False
return True