题解 | #对称的二叉树#
对称的二叉树
https://www.nowcoder.com/practice/ff05d44dfdb04e1d83bdbdab320efbcb
# class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param pRoot TreeNode类 # @return bool布尔型 # from collections import deque class Solution: def isSymmetrical(self , pRoot: TreeNode) -> bool: # write code here if not pRoot: return True queue = deque([pRoot.left, pRoot.right]) while queue: size = len(queue) if size % 2: return False level_values = [] for _ in range(size): node = queue.popleft() if node: level_values.append(node.val) queue.append(node.left) queue.append(node.right) else: level_values.append(None) if level_values != level_values[::-1]: return False return True
使用层次遍历直接对比每层的结果即可。