Skip to main content

32. Binary Tree Right Side View

mediumAsked at Meta

Return the last visible node at each tree level — Meta's comment-threading UI renders the rightmost visible reply at each nesting depth, and feed-ranking previews use this BFS level-order traversal pattern to surface the most prominent item per tier.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

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

Constraints

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

Examples

Example 1

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

Explanation: From the right side: level 0 → 1, level 1 → 3, level 2 → 4.

Example 2

Input
root = [1,null,3]
Output
[1,3]

Approaches

1. BFS level-order

Process the tree level by level with BFS. At the end of each level, the last node in the queue snapshot is the rightmost — append its value to the result.

Time
O(n)
Space
O(n)
function rightSideView(root) {
  if (!root) return [];
  const res = [], queue = [root];
  while (queue.length) {
    const levelSize = queue.length;
    for (let i = 0; i < levelSize; i++) {
      const node = queue.shift();
      if (i === levelSize - 1) res.push(node.val);
      if (node.left) queue.push(node.left);
      if (node.right) queue.push(node.right);
    }
  }
  return res;
}

Tradeoff:

2. DFS right-first (optimal)

DFS visiting right subtree before left. The first node visited at each depth is the rightmost — track by depth index. Same complexity, no queue allocation.

Time
O(n)
Space
O(h) recursion stack
function rightSideView(root) {
  const res = [];
  function dfs(node, depth) {
    if (!node) return;
    if (depth === res.length) res.push(node.val); // first visit = rightmost
    dfs(node.right, depth + 1);
    dfs(node.left, depth + 1);
  }
  dfs(root, 0);
  return res;
}

Tradeoff:

Meta-specific tips

Meta regularly asks this as a warm-up before harder tree problems. Interviewers want to see you articulate both BFS and DFS approaches — BFS is more intuitive for 'per-level' questions, but DFS with right-first traversal is elegant. The follow-up is often 'left side view' (trivial mirror) or 'all side views' — be ready to generalize.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill Binary Tree Right Side View and other Meta interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →