title: LEETCODE-DAY15
date: 2024-03-07 14:06:12
tags:
今日内容: 层序遍历 (共10题) 226.翻转二叉树 、101.对称二叉树 2
1.层序遍历(T102为模板)
class Solution:
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
res=list()
q=deque()
if root:
q.append(root)
while q:
level=list()#存放每一层的节点
size=len(q)
for i in range(size):
temp=q.popleft()
if temp.left:
q.append(temp.left)
if temp.right:
q.append(temp.right)
level.append(temp.val)
res.append(level)
return res
python语法:1.列表的嵌套:这里level也是一个列表
时间有点紧后面再补
2.翻转二叉树
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if not root:
return []
root.left,root.right=root.right,root.left
self.invertTree(root.left)
self.invertTree(root.right)
return root
TypeError: [] is not valid value for the expected return type TreeNode
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if not root:
return None
root.left,root.right=root.right,root.left
self.invertTree(root.left)
self.invertTree(root.right)
return root
AC
3.对称二叉树
class Solution:
def isSymmetric(self, root: Optional[TreeNode]) -> bool:
def leftTra(self,root):
res1=list()
if not root:
return []
left=leftTra(self,root.left)
right=leftTra(self,root.right)
return [root.val]+left+right
def rightTra(self,root):
res1=list()
if not root:
return []
right=leftTra(self,root.right)
left=leftTra(self,root.left)
return [root.val]+right+left
return leftTra(self,root)!=rightTra(self,root)
想法是leftTra以中左右遍历,rightTra以中右左遍历
root =
[1]
输出
false
预期结果
true
class Solution:
def isSymmetric(self, root: Optional[TreeNode]) -> bool:
return self.compare(root.left, root.right)
def compare(self, cur_left, cur_right):
#首先排除空节点的情况
if cur_left is None and cur_right is not None:
return False
elif cur_left is not None and cur_right is None:
return False
elif cur_left is None and cur_right is None:
return True
# 不为空的,但是值不想等
elif cur_left.val != cur_right.val:
return False
else:
# 左右节点不为空,且数字相等
outside = self.compare(cur_left.left,cur_right.right)
inside = self.compare(cur_left.right, cur_right.left)
return outside and inside