- categories: Code, Interview Question, leetcode, Medium
- source: https://leetcode.com/problems/binary-tree-right-side-view
- topics: Tree
Given the root
of a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
DFS
# 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 = {}
if not root:
return []
def dfs(node, depth):
nonlocal ans
if not depth in ans:
ans[depth] = node.val
if node.right:
dfs(node.right, depth + 1)
if node.left:
dfs(node.left, depth + 1)
dfs(root, 0)
return list(ans.values())