103. 二叉树的锯齿形层序遍历
给你二叉树的根节点 root ,返回其节点值的 锯齿形层序遍历 。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
解题思路:模仿层序遍历的方法,需要加一个层数指示器,当层数为偶数,则反转列表。
class Solution:
def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
if not root:
return []
# 结果
res = []
# 队列,存储下一层的节点
queue = [root]
# 指示方向,统计层数
count = 1
while queue:
cur_l = [] # 当前层的节点结果
cur_l_size = len(queue)
# 遍历当前层节点
for _ in range(cur_l_size):
node = queue.pop(0)
cur_l.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
# 如果是偶数层,则反转
if count % 2 == 0:
cur_l = cur_l[::-1]
res.append(cur_l)
count+=1
return res
236. 二叉树的最近公共祖先
从头开始找,类似于前序遍历,只不过这里只在遍历到指定节点时才能返回。
公共祖先是指两个节点的父节点或更上层节点相同。
1.先看看根节点,是不是符合要求
if not root or root == p or root == q:
return root
2.看看左右子树,先看左子树,里面有没有指定节点,再看右子树。
3.如果左子树和右子树都get到了,那返回根节点作为结果
4.如果左子树返回的节点为空,也就是左子树递归遍历出来没有找到指定节点,那就说明都在右子树,此时返回右子树返回的节点。
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
# 若不存在根节点,或者说p/q有一个是root,则返回根节点
if not root or root == p or root == q:
return root
# 递归,仿照前序遍历
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
# 若左右节点都在,也就是两个节点分别在两个子树中,则返回根节点
if left and right:
return root
# 如果左子树为空,那么p和q都在右子树中
if not left:
return right
else:
return left # 否则,p和q都在左子树中
104. 二叉树的最大深度
使用层序遍历的方式,每层遍历完后增加一个深度
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
# 空二叉树的处理
if not root:
return 0
# 当前层的队列
queue = [root]
# 初始化深度
depth = 0
# 没有遍历完的时候
while queue:
# 层序遍历
for _ in range(len(queue)):
i = queue.pop(0)
if i.left:
queue.append(i.left)
if i.right:
queue.append(i.right)
# 深度加一
depth += 1
return depth