代码思路:深度优先搜索,每次总访问右子树,value_depth用dict存放,深度为索引,存放节点的值,stack从根节点[(root, 0)]开始,添加node和depth
class Solution:def rightSideView(self, root: Optional[TreeNode]) -> List[int]:rightmost_value_at_depth = dict() # 深度为索引,存放节点的值max_depth = -1stack = [(root, 0)]while stack:node, depth = stack.pop()if node is not None:# 维护二叉树的最大深度max_depth = max(max_depth, depth)# 如果不存在对应深度的节点我们才插入rightmost_value_at_depth.setdefault(depth, node.val)stack.append((node.left, depth + 1))stack.append((node.right, depth + 1))return [rightmost_value_at_depth[depth] for depth in range(max_depth + 1)]