Binary Tree Right Side View

MediumTrees · BFS / DFS by Depth🧩 Tree BFS (Level Order)LeetCode #199 ↗Updated

Problem

Picture yourself standing to the right of a binary tree. Return the values of the nodes you can see, from the top level down — that is, the last (rightmost) node of every level. A left-subtree node is visible if nothing at its depth lies to its right.
Input[1,2,3,null,5,null,4]Output[1,3,4]
Input[1,2,3,4]Output[1,3,4]
Input[]Output[]

0 ≤ nodes ≤ 100  ·  -100 ≤ Node.val ≤ 100

Try it yourself

Java
class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
The answer has exactly one value per depth. Visit nodes so that the first node seen at each new depth is the rightmost one: a DFS that goes right before left does exactly that.
PatternTree BFS (Level Order)

Instinct The answer talks about levels, rows, depth order, "closest to the root" or what you see from a side? Queue the tree and process it one level at a time.

Memory hack Freeze the size, drain the row - read n = queue.size() before the loop and one level never bleeds into the next.

Open the Tree BFS (Level Order) guide →

Approaches

Brute ForceHeight + Rightmost Search per Depth

Time O(n · h)Space O(h)

For each depth d below the height, run a separate right-first DFS that returns the first node it meets at depth d. Correct, but the top of the tree is re-explored for every level.

Java
public List<Integer> rightSideView(TreeNode root) {
    List<Integer> res = new ArrayList<>();
    int h = height(root);
    for (int d = 0; d < h; d++) res.add(rightmost(root, d).val);
    return res;
}
private int height(TreeNode node) {
    return node == null ? 0 : 1 + Math.max(height(node.left), height(node.right));
}
// first node reached at depth d, exploring right before left
private TreeNode rightmost(TreeNode node, int d) {
    if (node == null) return null;
    if (d == 0) return node;
    TreeNode r = rightmost(node.right, d - 1);
    return r != null ? r : rightmost(node.left, d - 1);
}

Easy to justify, but a skewed tree (h = n) makes it O(n²).

At a glance

LevelApproachTimeSpace
Brute ForceHeight + Rightmost Search per DepthO(n · h)O(h)
BetterBFS — Last Node of Each LevelO(n)O(w)
OptimalDFS — Right Child FirstO(n)O(h)
Common pitfalls
  • Following only right pointers — misses left nodes visible below a short right side.
  • BFS: recording the first node of each level instead of the last.
  • DFS: visiting left before right, so the leftmost node claims the depth.
Interview tips
  • Clarify with a tree whose left side is deeper (e.g. [1,2,3,4] → 4 is visible).
  • Rephrase as “last node of each level” — BFS then becomes obvious.
  • Offer the right-first DFS and compare O(h) vs O(w) space.
Pattern
One answer per depth → BFS with a level snapshot, or DFS with depth == res.size() as the “first visit” test.
My notes saved in this browser