给定一个二叉树,检查它是否是镜像对称的。
一刷:
递归:
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if root==None:
return True
def check(left: TreeNode, right:TreeNode) -> bool:
if left==None and right==None:
return True
if left==None or right==None:
return False
if left.val != right.val:
return False
return check(left.left, right.right) and check(left.right, right.left)
return check(root.left, root.right)
迭代:
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if root==None:
return True
queue = [root.left, root.right]
while(queue):
n = len(queue)
current = [None for i in range(n*2)]
num = 0
for i in range(n//2):
if queue[i] == None and queue[n-i-1] == None:
num += 2
if num == n:
return True
continue
if queue[i] == None or queue[n-i-1] == None:
return False
if queue[i].val != queue[n-i-1].val:
return False
current[i*2] = queue[i].left
current[i*2+1] = queue[i].right
current[(n-i-1)*2] = queue[n-i-1].left
current[(n-i-1)*2+1] = queue[n-i-1].right
queue = current