# 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
return self.isS(root.left,root.right)
def isS(self,left,right):
if not left and not right:
return True
if left and not right:
return False
if not left and right:
return False
if left.val!=right.val :
return False
return self.isS(left.left,right.right) and self.isS(left.right,right.left)
迭代:
# 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
nlist=[root.left,root.right]
while(len(nlist)>0):
l=nlist.pop(-1)
r=nlist.pop(-1)
if not r and not l:
continue
elif not r or not l:
return False
elif l.val!=r.val:
return False
nlist.append(l.left)
nlist.append(r.right)
nlist.append(l.right)
nlist.append(r.left)
return True
本文介绍了一种检查二叉树是否对称的有效方法,包括递归和迭代两种算法实现,通过比较左子树和右子树的镜像来判断整个树的对称性。
379

被折叠的 条评论
为什么被折叠?



