LeetCode #199 Medium

Binary Tree Right Side View

Binary Tree Right Side View is LeetCode 199 (Medium). Imagine standing to the right of a binary tree: return the values of the nodes you can see, from top to bottom.

  • You see exactly one node per level, the rightmost node on that level.
  • The tree can be empty; then the answer is [].

With at most 100 nodes, a single O(n) walk is all that is needed.

Constraints
  • The number of nodes in the tree is in the range [0, 100].
  • -100 <= Node.val <= 100
treebfsdfs
Open on LeetCode ↗
02

Intuition

Seeing one node per level does not mean following right children down. When the left subtree is deeper, its lower nodes stick out below the right side and are visible too.

So think per depth. A depth-first search that visits the right child before the left, carrying the depth, meets each node in one of two situations:

  • First node at its depth: everything to its right at that depth was searched earlier and nothing was there, so it is the visible one.
  • A later node at that depth: a node further right already covers it, so it is hidden.

The answer list tells the two apart: its length is the number of depths already seen.

How to spot this pattern

Any question that wants one node per level, such as the right view, the left view, the largest value in each row or the bottom-left value, can be solved two ways: a BFS that handles one level at a time, or a DFS that carries the depth and compares it with the length of the answer.

03

Approach

Try it first

Before reading on: in [1,2,3,4], node 3 has no children but node 2 has a child 4. Which nodes can you see from the right, and why is 4 one of them even though it sits on the left side?

1

Visit with the depth

Call dfs(node, depth) starting with (root, 0); an empty node returns at once. The depth is an argument, so each call knows its own level and nothing has to be reset when a call returns.

2

Record the first node at each depth

If depth == len(view), no node at this depth has been recorded yet, so append node.val. Otherwise this depth already has its visible node, and the current one is hidden behind it.

3

Go right, then left

Recurse into node.right with depth + 1, then into node.left. Right first makes the first arrival at each depth the rightmost node there. The left subtree is still searched, because it can reach depths the right side never does.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
▶3 view = []
▶4 
▶5 def dfs(node, depth):
▶6 if not node:
▶7 return
▶8 if depth == len(view):
▶9 view.append(node.val)
▶10 dfs(node.right, depth + 1)
▶11 dfs(node.left, depth + 1)
▶12 
▶13 dfs(root, 0)
▶14 return view
hiddenin viewdepth 0depth 1depth 212354view10depth 0 is new → add 1
node1the root
depth0view has 0 values
view[1]
Start at the root, depth 0. The view is empty, so its length 0 equals the depth: nothing at this depth has been recorded, and the root is the only node there. Add 1.
hiddenin viewdepth 0depth 1depth 212354view1031depth 1 is new → add 3
node3right child of 1
depth1view has 1 value
view[1, 3]
3 is the first node reached at depth 1: the view holds 1 value, one per shallower depth. Because the search always tries right before left, nothing further right exists at this depth, so 3 is the visible one.
hiddenin viewdepth 0depth 1depth 212354view103142depth 2 is new → add 4
node4right child of 3
depth2view has 2 values
view[1, 3, 4]
4 is the first node reached at depth 2: the view holds 2 values, one per shallower depth. Because the search always tries right before left, nothing further right exists at this depth, so 4 is the visible one.
hiddenin viewdepth 0depth 1depth 212354view103142depth 1 already seen → 2 is hidden
node2left child of 1
depth1view has 3 values
covered by3further right
Depth 1 already has 3, which was reached earlier and is further right. So 2 is hidden behind it and the view does not change. The search still goes below 2, because its subtree may reach a depth not seen yet.
hiddenin viewdepth 0depth 1depth 212354view103142depth 2 already seen → 5 is hidden
node5right child of 2
depth2view has 3 values
covered by4further right
Depth 2 already has 4, which was reached earlier and is further right. So 5 is hidden behind it and the view does not change. It is a leaf, so this branch ends here.
hiddenin viewdepth 0depth 1depth 212354view103142return [1, 3, 4]
view[1, 3, 4]one node per depth
visited5 nodesO(n)
Done. Every node was visited once. The view has one value per depth, 3 in all, and each is the first node the right-first search reached at that depth.
05

Level-by-level BFS

A queue holds one level at a time, left to right. Before a level is processed, the last node in the queue is the rightmost on that level, so its value goes into the answer; then the level's nodes are dequeued and their children enqueued.

▶1class Solution:
▶2 def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
▶3 if not root:
▶4 return []
▶5 view, queue = [], deque([root])
▶6 while queue:
▶7 view.append(queue[-1].val)
▶8 for _ in range(len(queue)):
▶9 node = queue.popleft()
▶10 if node.left:
▶11 queue.append(node.left)
▶12 if node.right:
▶13 queue.append(node.right)
▶14 return view
06

Common pitfalls

Following only the right children

✗ Wrong
node = root
while node:
    view.append(node.val)
    node = node.right
✓ Right
dfs(node.right, depth + 1)
dfs(node.left, depth + 1)

Nodes of a deeper left subtree are visible too. For [1,2,3,4] this returns [1, 3], but 4 is visible below 3, so the answer is [1, 3, 4].

Recursing left before right

✗ Wrong
dfs(node.left, depth + 1)
dfs(node.right, depth + 1)
✓ Right
dfs(node.right, depth + 1)
dfs(node.left, depth + 1)

The first node reached at each depth is then the leftmost one, so the code returns the left side view. For [1,2,3] it gives [1, 2] instead of [1, 3].

07

Complexity

Time
O(n)
Space
O(h)
Each node is visited once. The recursion holds one root-to-node path: about log n calls for a balanced tree, n for a chain.
08

Binary Tree Right Side View FAQ

Is GFG Right View of Binary Tree the same problem?

Yes. The GeeksforGeeks version asks for the same nodes in the same top-to-bottom order, so this code works there unchanged.

How do you get the left view instead?

Visit the left child before the right one; the first node at each depth is then the leftmost. In the BFS version, record the first node of each level instead of the last.