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
UnverifiedIdea. 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.
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.