150NeetCode 150

54.Binary Tree Right Side View

MediumTrees ยท 9/15

Problem

Given the root of a binary tree, imagine standing on its right side. Return the values of the nodes you can see, ordered from top to bottom.

On each level you see exactly one node: the rightmost node of that level. Note that this node is not always a right child โ€” if a level's right side is empty, a node from a left branch becomes visible.

Examples

Input:  root = [1,2,3,null,5,null,4]
Output: [1,3,4]
Input:  root = [1,2,3,4,null,null,null,5]
Output: [1,3,4,5]
Explanation: Levels 3 and 4 only exist under the left child 2, so 4 and 5 are visible.
Input:  root = []
Output: []

Constraints

  • The number of nodes in the tree is in the range [0, 100].
  • -100 <= Node.val <= 100

๐Ÿ’ก Key Insight

The answer is "the last node of every level". A BFS that processes one level per round can record the last node polled in each round. Alternatively, a DFS that visits right before left reaches the rightmost node of each depth first, so the first node seen at every new depth is the visible one.

Full Level Order, Then Take Last

TimeO(n)SpaceO(n)

Intuition

Reuse the standard level order traversal to build every level as a list, then read off the last element of each list. Correct and simple, but it stores every value even though only one per level is needed.

Algorithm

  1. Run BFS and build levels, a list of per-level value lists.
  2. For each level in levels, append level.get(level.size() - 1) to the result.

Visualization

root = [1,2,3,null,5,null,4]

levels = [[1], [2, 3], [5, 4]]
last of each -> [1, 3, 4]

Code

java
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<List<Integer>> levels = new ArrayList<>();
        if (root != null) {
            Deque<TreeNode> queue = new ArrayDeque<>();
            queue.offer(root);
            while (!queue.isEmpty()) {
                int size = queue.size();
                List<Integer> level = new ArrayList<>();
                for (int i = 0; i < size; i++) {
                    TreeNode node = queue.poll();
                    level.add(node.val);
                    if (node.left != null) queue.offer(node.left);
                    if (node.right != null) queue.offer(node.right);
                }
                levels.add(level);
            }
        }
        List<Integer> result = new ArrayList<>();
        for (List<Integer> level : levels) {
            result.add(level.get(level.size() - 1)); // rightmost value
        }
        return result;
    }
}

Complexity

  • Time: O(n) โ€” BFS plus one pass over the levels.
  • Space: O(n) โ€” every value is stored in levels.

Complexity Comparison

Approach Time Space
Full Level Order, Then Take Last O(n) O(n)
DFS, Right Child First O(n) O(h)
BFS, Last Node per Level O(n) O(w)

Common Pitfalls

  • Only following right pointers from the root โ€” this misses nodes like 4 and 5 in example 2 that are visible because the right side is shorter.
  • In the DFS version, visiting left before right records the leftmost node of each level instead.
  • In BFS, enqueuing right before left while still taking the last polled node gives the left view.
  • Forgetting the empty-tree case.