CodeArchon

mediumTreesGoogleFacebookAmazonUber

East Horizon View

Standing on the Eastern horizon of a forest development lot, a surveyor logs only the tallest, outermost branches visible.

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.

Choose approach

1
✓
scan
2
3
5
4
1/9
Narrationstep 1 of 9

Visit Node 1 at height depth tier 0. First rightmost node found!

1def rightSideView(root: Optional[TreeNode]) -> List[int]:
2 result = []
3 def dfs(node: Optional[TreeNode], depth: int):
4 if not node:
5 return
6 if depth == len(result):
7 result.append(node.val)
8 dfs(node.right, depth + 1)
9 dfs(node.left, depth + 1)
10 dfs(root, 0)
11 return result
Variables
currNode=1
depth=0
currentViewLength=1
isFirstAtDepth=true
eastHorizonResult=[1]

How to think about it

  1. Navigate starting on the right-hand child.
  2. If recursion depth matches current array size, it represents the first element seen on that tier level.
  3. Push node value to result, then search remaining left pathways recursively.

Edge cases to catch in interview

  • Single branch left-side tree -> right-view still harvests left nodes if they are the only ones at their depth.
  • Vacant root tree -> returns blank list.

Examples

Example 1[1, 3, 4]
{"arr":[1,2,3,null,5,null,4]}
Example 2[1, 3]
{"arr":[1,null,3]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed