Binary Tree Right Side View, explained
The right side view of a binary tree is the list of nodes you would see looking at it from the right: exactly one node per level, the rightmost one. Get it with a level-by-level breadth-first search that keeps the last node of each level, or with a depth-first search that visits right children first and records the first node it reaches at each new depth. Both are O(n).
By Evin JohnPublished 7 min read
What you see from the right
Imagine standing to the right of a drawn binary tree and looking left. On each level you see only the node closest to you, and nodes further left on the same level are hidden behind it. Return the values you see, from the root level downward. An empty tree gives an empty list.
7
/ \
3 9
/ \
2 5
/
1The first two answers are easy: 7, then 9. On the third level, 9 has no children, so the rightmost node is 5, a right child of the left subtree. On the fourth level only 1 exists, and it is a left child of a left child. A tree that is a chain of left children shows every node. Ask whether the interviewer also wants the left view, since the same code covers it with one change.
What the interviewer is checking
The tempting wrong answer is to follow right pointers from the root until they run out. On the drawing that gives [7, 9] and misses two levels. The question checks whether you think in levels rather than in pointers, and whether you can pick either traversal and adapt it. If you have practiced Binary Tree Level Order Traversal, this is a short step from there.
A simple first version: collect every level
Build the full list of values for each level, top to bottom and left to right, then return the last value of each. It is correct and quick to write. It stores every value in the tree, O(n) memory, when the answer only needs one value per level.
def all_levels(root):
levels = []
def visit(node, depth):
if node is None:
return
if depth == len(levels):
levels.append([])
levels[depth].append(node.val)
visit(node.left, depth + 1)
visit(node.right, depth + 1)
visit(root, 0)
return levels
def view_from_right_slow(root):
return [row[-1] for row in all_levels(root)]Breadth-first: last node per level
Run breadth-first search with a queue, but process one level at a time. At the start of each level, the queue holds exactly that level's nodes, so record its length. Pop that many nodes, pushing their children for the next level, and keep the value of the last one popped. Nothing else needs storing. The queue's peak size is the widest level of the tree.
from collections import deque
def view_from_right(root):
seen = []
if root is None:
return seen
queue = deque([root])
while queue:
width = len(queue)
for i in range(width):
node = queue.popleft()
if i == width - 1:
seen.append(node.val) # rightmost node of this level
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return seenDepth-first: right child first
Depth-first search can do the same with less code. Visit the right child before the left, and pass the depth down. The first time the search reaches a given depth, it must be at the rightmost node of that level, because every node to its right on that level would have been visited earlier. So record a value whenever the depth equals the length of the answer so far, meaning this depth has not been seen yet.
function viewFromRight(root) {
const seen = [];
const visit = (node, depth) => {
if (node === null) return;
if (depth === seen.length) seen.push(node.val); // first node met at this depth
visit(node.right, depth + 1); // right side first
visit(node.left, depth + 1);
};
visit(root, 0);
return seen;
}Trace the drawing with the depth-first version. Depth 0 records 7. Going right, depth 1 records 9, which has no children. Back to 3 at depth 1, already recorded, so nothing. Its right child 5 is the first node at depth 2, recorded. Then 2 at depth 2 is skipped, and its child 1 is the first at depth 3. Result: [7, 9, 5, 1]. For the left view, visit left before right.
Complexity
| Approach | Time | Extra space |
|---|---|---|
| Collect every level, keep the last | O(n) | O(n) for all levels |
| Breadth-first, last per level | O(n) | O(w) for the queue |
| Depth-first, right child first | O(n) | O(h) for recursion |
Which is better depends on shape. A wide, shallow tree favors depth-first, since its height is small and its widest level is large. A deep, narrow tree favors breadth-first, and it also avoids recursion limits in Python. Saying that out loud is a good way to show judgment rather than habit.
Inputs to try
- Empty tree: empty list.
- Only left children: every node appears.
- Only right children: every node appears.
- A short right subtree and a deep left one, like the drawing.
- A complete tree: the rightmost path, top to bottom.
Where it goes wrong
- Following right pointers only, which misses levels where the right side ends early.
- In the breadth-first version, reading
len(queue)inside the loop instead of once per level, which mixes levels together. - In the depth-first version, visiting left before right and getting the left view by accident.
- Recording the first node per depth with a set of seen depths, which works but is extra state the answer list already provides.
Follow-ups
- Left side view. Keep the first node per level in breadth-first, or visit left first in depth-first.
- Both side views at once. In breadth-first, record the first and last node of each level in the same loop.
- Top view or bottom view. Track a horizontal position as well as depth, and keep the first or last node per column.
- An n-ary tree. Visit children from last to first in depth-first search; breadth-first is unchanged.
How to say it
Fictional example
- Candidate
- The visible node on each level is the rightmost one, which isn't always a right child. So I need to think per level, not follow right pointers.
- Candidate
- I'll do breadth-first search, one level at a time: measure the queue, pop that many nodes, and keep the last one's value.
- Candidate
- Alternatively, depth-first with the right child first records the first node at each new depth. Both are linear; I'd pick based on whether the tree is wide or deep.
Related problems
Count Good Nodes in Binary Tree also carries information down a depth-first search. Lowest Common Ancestor and Diameter of Binary Tree pass answers up instead. The coding problems hub groups every walkthrough by pattern.
Practicing with Natively
Natively, on Mac or Windows, can read a tree drawing like the one above from a screenshot during practice and explain why the third level shows 5 rather than nothing, or compare the queue and depth-first versions with you. It also writes a transcript of each mock session, which helps you review whether you talked about wide versus deep trees. The AI interview assistant page explains how sessions are kept.
Questions people ask
How do you solve Binary Tree Right Side View?
Run breadth-first search one level at a time and keep the value of the last node in each level. Or run depth-first search visiting right children first and record the first node reached at each new depth. Both are O(n).
Why not just follow the right children from the root?
The visible node on a level can be a left child, or a node in the left subtree, whenever the right side of the tree is shorter. Following right pointers misses those levels.
Should I use BFS or DFS for the right side view?
Either is fine. BFS uses memory proportional to the widest level; DFS uses memory proportional to the height. Pick based on the tree's shape, and prefer BFS for very deep trees in languages with recursion limits.
How do you get the left side view instead?
Keep the first node of each level in BFS, or visit the left child before the right in DFS.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
