# 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