LeetCode199 二叉树的右视图(bfs)
bfs记录每层最后一位被遍历的节点值
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
ans, depth, queue = {}, -1, [(root, 0)]
while queue:
cur_root, cur_depth = queue.pop(0)
if cur_root:
depth = max(depth, cur_depth)
ans[cur_depth] = cur_root.val
queue.append((cur_root.left, cur_depth + 1))
queue.append((cur_root.right, cur_depth + 1))
return [ans[i] for i in range(depth + 1)]