题目
解法
解法1 层序遍历修改
自己一开始只想到这种做法,层序遍历的过程中判断当前层的结果是否是回文。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def judge(self, x):
if len(x)==0:
return True
if len(x)%2==1:
return False
i = 0
j = len(x)-1
while i<j:
if x[i]!=x[j]:
return False
i = i+1
j = j-1
return True
def isSymmetric(self, root: TreeNode) -> bool:
if not root:
return True
queue = [root]
while len(queue)>0:
length = len(queue)
row = []
while length>0:
cur = queue.pop(0)
if cur.left:
queue.append(cur.left)
row.append(cur.left.val)
else:
row.append(-1)
if cur.right:
queue.append(cur.right)
row.append(cur.right.val)
else:
row.append(-1)
length = length-1
if not self.judge(row):
return False
return True
解法二 递归
一开始没想到这种解法,看了解析后才想到的
# 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:
def cur(left, right):
if left is None and right is None:
return True
if left is None or right is None:
return False
if left.val != right.val:
return False
return cur(left.left, right.right) and cur(left.right, right.left)
if not root:
return True
return cur(root.left, root.right)