Skip to content
DSA Patterns
Menu
Language
Tree BFSLC #1993 of 6← PreviousNext →

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Mediumtree-bfs

Binary Tree Right Side View

Problem (restated)

Return the values of nodes visible from the right side (top to bottom).

Intuition

BFS by levels; the last node in each level is the rightmost.

Approaches

Level-order last node

Unverified
Time O(n)Space O(w)

Idea. standard level queue; append level[^1].val each round.

Walkthrough. [1,2,3,null,5,null,4] → [1,3,4].

Trade-offs. DFS with depth map also works; BFS is the tree-bfs template.

Solution
Show helper code
export class TreeNode {
  val: number;
  left: TreeNode | null;
  right: TreeNode | null;
  constructor(val = 0, left: TreeNode | null = null, right: TreeNode | null = null) {
    this.val = val; this.left = left; this.right = right;
  }
}
export class TreeNode {
  val: number;
  left: TreeNode | null;
  right: TreeNode | null;
  constructor(val = 0, left: TreeNode | null = null, right: TreeNode | null = null) {
    this.val = val; this.left = left; this.right = right;
  }
}
export function rightSideView(root: TreeNode | null): number[] {
  if (!root) return [];
  const res: number[] = [];
  let level: TreeNode[] = [root];
  while (level.length) {
    const next: TreeNode[] = [];
    res.push(level[level.length - 1]!.val);
    for (const n of level) {
      if (n.left) next.push(n.left);
      if (n.right) next.push(n.right);
    }
    level = next;
  }
  return res;
}
export function rightSideView(root: TreeNode | null): number[] {
  if (!root) return [];
  const res: number[] = [];
  let level: TreeNode[] = [root];
  while (level.length) {
    const next: TreeNode[] = [];
    res.push(level[level.length - 1]!.val);
    for (const n of level) {
      if (n.left) next.push(n.left);
      if (n.right) next.push(n.right);
    }
    level = next;
  }
  return res;
}

Template connection

Level snapshot, and the level’s answer is the last node popped in that round. That node is the rightmost one.

Reflection

  • The last node of each level is the right-side view. Walking only the right spine misses a left child whose right sibling is missing.
  • Scanning left to right and keeping the last node is the same node as scanning right to left and keeping the first.
  • A null root is empty. One node is itself.
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 6
1/6

Right side view of 1 / 2, 3 / 5, 4. The last node of each BFS level is the one you see from the right.

1q2354

view = [] · queue = [1]

Key:CurrentActive rangeMatchSettled