Binary Tree Right Side View

Difficulty: Medium

Imagine standing to the right of a binary tree. You'd see only the rightmost node at each level; it hides the nodes behind it.

Given the root of a binary tree, return the values you can see from the right side, from the top level to the bottom.

Examples

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

Level 0 shows 1. Level 1 shows 3 (2 is hidden behind it). Level 2 shows 4 (5 is hidden behind it).

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

Every level here has only one node, so both are visible.

Input: root = []
Output: []

An empty tree has nothing to view.

Constraints

  • The number of nodes in the tree is in the range [0, 100].

  • -100 <= Node.val <= 100

Approach

The visible node at each level is the rightmost one. A level-order (BFS) traversal already groups nodes by level, so take the last value in each level.

Or use a depth-first traversal that visits the right child first. It reaches the rightmost node of each depth first, so record the first value seen at each new depth and never overwrite it.

Solutions

Iterative BFS

Do a normal level-order traversal with a queue, but keep only the last node's value in each level.

class TreeNode {
  constructor(val, left = null, right = null) {
    this.val = val;
    this.left = left;
    this.right = right;
  }
}

function rightSideView(root) {
  if (root === null) return [];

  const result = [];
  const queue = [root];

  while (queue.length > 0) {
    const levelSize = queue.length;

    for (let i = 0; i < levelSize; i++) {
      const node = queue.shift();

      if (i === levelSize - 1) {
        result.push(node.val);
      }

      if (node.left) queue.push(node.left);
      if (node.right) queue.push(node.right);
    }
  }

  return result;
}

Time: O(n) · Space: O(n) — the queue can hold up to a whole level of nodes

Recursive DFS (Right First)

Do a depth-first traversal that visits the right child before the left. The first node reached at each depth is the rightmost one, so record it and never overwrite it.

function rightSideView(root) {
  const result = [];

  function dfs(node, depth) {
    if (node === null) return;

    if (depth === result.length) {
      result.push(node.val);
    }

    dfs(node.right, depth + 1);
    dfs(node.left, depth + 1);
  }

  dfs(root, 0);
  return result;
}

Time: O(n) · Space: O(h) — recursion stack depth, plus O(h) for the result array