Skip to problem
←

Binary Tree Right Side View

Medium 0 attempts

You're given the root of a binary tree. Imagine standing to its right and looking at the tree edge-on: return the value of the rightmost node visible at each level, ordered from the top level down.

Function contract

Implement rightSideView(root). The runner converts the level-order input array into nodes with val, left, and right fields; [] becomes null.

Output: An array containing the rightmost node at each depth, from top to bottom. Return [] for an empty tree.

Example 1

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

Example 2

Input
root = []
Output
[]
Visual Aid
The visible node can come from the left subtree
1234Right-side view: [1, 3, 4]

In this additional example, node 4 is visible because there is no node to its right at that depth.

Constraints
  • 0 <= number of nodes <= 100
  • -100 <= Node.val <= 100

BFS Level Order (Last of Each Level)

javascript
function rightSideView(root) {
  if (!root) return [];
  const result = [], q = [root];
  let head = 0;
  while (head < q.length) {
    const size = q.length - head;
    for (let i = 0; i < size; i++) {
      const node = q[head++];
      if (i === size - 1) result.push(node.val);
      if (node.left) q.push(node.left);
      if (node.right) q.push(node.right);
    }
  }
  return result;
}

Time: O(n) | Space: O(n)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript