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
UnverifiedTime 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
- Walk one level and take that row’s maximum. Starting the max at 0 is wrong on a negative row; start from the first node.
- An empty tree is an empty list. One node is that value. A tied maximum is written once.
- Order inside the row does not matter. Children are still pushed left to right.