给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树
[1,2,2,3,4,4,3]
是对称的。1 / \ 2 2 / \ / \ 3 4 4 3但是下面这个
[1,2,2,null,3,null,3]
则不是镜像对称的:1 / \ 2 2 \ \ 3 3说明:
如果你可以运用递归和迭代两种方法解决这个问题,会很加分。
tips: 二叉树的问题基本上都可以用递归去做,对称二叉树只需要判断左子树的左节点和右子树的右节点记忆左子树的右节点和右子树的左节点是否一致。
递归代码:
def isSymmetric(self, root: TreeNode) -> bool:
def dg(root1,root2):
if (not root1 and root2) or (not root2 and root1):
return False
if not root1 and not root2:
return True
if root1.val!=root2.val:
return False
return dg(root1.left,root2.right) and dg(root1.right,root2.left)
return dg(root,root)
按层次遍历代码:
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
def bfs(root):
if not root:
return True
queue=[root]
res=[]
now,last=root,root
while queue:
pop=queue.pop()
res.append(pop.val)
if pop.left:
queue.insert(0,pop.left)
else:
queue.insert(0,TreeNode(-9999))
if pop.right:
queue.insert(0,pop.right)
else:
queue.insert(0,TreeNode(-9999))
now=queue[0]
if pop == last:
last=now
if res!=res[::-1]:
return False
cnt=0
for r in res:
if r==-9999:
cnt+=1
if cnt==len(res):
return True
res=[]
return bfs(root)