Mediumtree-bfs
Find Largest Value in Each Tree Row
Problem (restated)
Return an array of the largest value in each level of a binary tree.
Intuition
Standard level BFS; track max while scanning each level size.
Approaches
Level BFS max
Tested onlyTime O(n)Space O(w)
Idea. For each level, max over the level array.
Walkthrough. Levels [1], [3,2], [5,3,9] → [1,3,9].
Trade-offs. BFS natural; DFS with depth also works.
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 largestValues(root: TreeNode | null): number[] {
if (!root) return [];
const res: number[] = [];
const q: TreeNode[] = [root];
while (q.length) {
const size = q.length;
let m = -Infinity;
for (let i = 0; i < size; i++) {
const n = q.shift()!;
m = Math.max(m, n.val);
if (n.left) q.push(n.left);
if (n.right) q.push(n.right);
}
res.push(m);
}
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 largestValues(root: TreeNode | null): number[] {
if (!root) return [];
const res: number[] = [];
const q: TreeNode[] = [root];
while (q.length) {
const size = q.length;
let m = -Infinity;
for (let i = 0; i < size; i++) {
const n = q.shift()!;
m = Math.max(m, n.val);
if (n.left) q.push(n.left);
if (n.right) q.push(n.right);
}
res.push(m);
}
return res;
}
Template connection
Tree BFS per-level aggregate.
Reflection
- Which pattern gave this away within 90 seconds?
- What changed from the standard template?
- What would break the current solution?