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
Tested onlyTime 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
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[] = [];
const q: TreeNode[] = [root];
while (q.length) {
const size = q.length;
for (let i = 0; i < size; i++) {
const n = q.shift()!;
if (i === size - 1) res.push(n.val);
if (n.left) q.push(n.left);
if (n.right) q.push(n.right);
}
}
return res;
}
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[] = [];
const q: TreeNode[] = [root];
while (q.length) {
const size = q.length;
for (let i = 0; i < size; i++) {
const n = q.shift()!;
if (i === size - 1) res.push(n.val);
if (n.left) q.push(n.left);
if (n.right) q.push(n.right);
}
}
return res;
}
Template connection
Tree BFS level answers.
Reflection
- Which pattern gave this away within 90 seconds?
- What changed from the standard template?
- What would break the current solution?