題目:
題解:
class Solution:def rightSideView(self, root: 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)]