Binary Tree Right Side View (LeetCode 199): Solution and Explanation

Medium
Tree
Depth First Search
Breadth First Search
Binary Tree

Imagine standing to the right of a binary tree and looking at it. Return the values of the nodes you can see, from top to bottom, which is the rightmost node on each level.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

A common first guess is to follow right children from the root down. That fails as soon as a left subtree is deeper than the right one. In a tree where the root's right child is a leaf but the left child has descendants, those deeper left nodes are still visible from the right, because nothing on their level is further right.

So the question is really about levels, not about right pointers. For every depth in the tree, you want the last node you would meet scanning that level from left to right. That is exactly what level-order traversal, breadth-first search, gives you: it processes the tree one level at a time, left to right.

The reference code runs BFS with a queue and measures the queue length at the start of each level, so it knows exactly how many nodes belong to that level. While it processes them, it keeps overwriting rightSide with each real node, so when the level finishes, rightSide holds the rightmost node. It appends that node's value and moves on.

One detail of this implementation is that it pushes children even when they are None and skips None entries when they are popped. That keeps the code short, and it is also why the if rightSide check matters: the final level consists only of None placeholders and must not add anything to the answer.

Approach: Level-order BFS

  1. Create res and a queue q initialized with the root.
  2. While the queue is non-empty, set rightSide = None and record qLen = len(q), the size of the current level.
  3. Pop qLen entries. For each non-None node, set rightSide = node and enqueue its left and right children, even if they are None.
  4. After the level is processed, if rightSide is not None, append rightSide.val to res.
  5. When the queue is empty, return res.

Step-by-step example

root = [1,2,3,null,5,null,4]
  1. Level 1: the queue holds node 1. Processing it sets rightSide = 1 and enqueues 2 and 3. Append 1.
  2. Level 2: process 2 (enqueue None and 5), then 3 (enqueue None and 4). The last real node is 3, so append 3.
  3. Level 3: the queue holds None, 5, None, 4. Skipping the Nones, rightSide becomes 5 and then 4, and their None children are enqueued. Append 4.
  4. Level 4: the queue holds only None entries, so rightSide stays None and nothing is appended. The queue empties.
  5. The result is [1, 3, 4]. Node 5 is hidden behind node 4 on the same level.

Code: Python, Java, C++

1class Solution:
2    def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
3        res = []
4        q = deque([root])
5        
6        while q:
7            rightSide = None
8            qLen = len(q)
9            
10            for i in range(qLen):
11                node = q.popleft()
12                if node:
13                    rightSide = node
14                    q.append(node.left)
15                    q.append(node.right)
16            
17            if rightSide:
18                res.append(rightSide.val)
19        return res

Time and space complexity

Time

O(n)

Every node is enqueued and dequeued once, along with at most n + 1 None placeholders.

Space

O(n)

The queue holds at most one full level plus placeholders, which can be about n / 2 nodes in a complete tree.

Other approaches

DFS visiting right child first (time O(n), space O(h))

Do a depth-first traversal that goes right before left, carrying the depth. The first node seen at each new depth is the rightmost one, so append it when depth == len(res). It uses O(h) space, which is better for wide, shallow trees.

BFS without None placeholders (time O(n), space O(n))

Only enqueue children that exist and take the last node popped in each level. It does slightly less work and avoids the extra None check, while following the same idea.

Common mistakes

  • Following only right children from the root. Deeper nodes in the left subtree are visible when the right subtree is shorter.
  • Reading len(q) inside the inner loop instead of saving it first, which mixes nodes from the next level into the current one.
  • Appending rightSide.val without checking for None. With placeholder children, the last level contains only None entries.
  • In the DFS version, visiting the left child first, which records the leftmost node at each depth instead of the rightmost.

Frequently asked questions

BFS or DFS for Binary Tree Right Side View?

Both work in O(n) time. BFS is the most direct since it processes one level at a time, while a right-first DFS uses only O(h) space and records the first node it reaches at each depth.

Why isn't the answer just the rightmost path?

If the right subtree is shorter than the left, the deeper levels have no right-side nodes, and their rightmost node comes from the left subtree. Those nodes are still visible from the right.

What is the time complexity?

It is O(n), since every node is visited once. Space is O(n) for the BFS queue, or O(h) for the DFS version.

How would you get the left side view?

Keep the first node of each level instead of the last in BFS, or visit the left child before the right in DFS.