Find Largest Value in Each Tree Row
Medium
Topics
Given the root of a binary tree, return an array containing the largest value in each row (level), ordered from the top row to the bottom row.
Example 1
largest on its level
One maximum per level, top down:
[1, 3, 9].Tree given in level-order (breadth-first);
null marks a missing child.Input: root = [1,3,2,5,3,null,9] Output: [1,3,9]
Example 2
largest on its level
Input: root = [1,2,3] Output: [1,3]
Constraints
- 0 <= number of nodes <= 10^4
- -2^31 <= Node.val <= 2^31 - 1
Editorial — intuition, approach, complexity and pitfalls
Intuition
One value per level, so process the tree a level at a time and take each level's maximum. The level-order BFS pattern again: capture the queue's length before the inner loop, and that count is exactly the level's width.
A DFS also works — carry the depth, and for each node either append its value (if this depth is new) or fold it into the existing entry with max. Same O(n) time, O(h) space instead of O(w), which is the better trade on a wide shallow tree.
Approach
- Return empty for an empty tree.
- For each level, scan its nodes tracking the maximum and enqueuing children.
- Append the maximum.
Dry Run
tree 1
/ \
3 2
/ \ \
5 3 9
level 0 [1] max 1
level 1 [3,2] max 3
level 2 [5,3,9] max 9
answer [1,3,9]Complexity
- Time — O(n): each node visited once.
- Space — O(w): the queue holds one level, up to about n/2 on a complete tree. The DFS variant is O(h).
Common Pitfalls
- Initialising the per-level maximum to 0. Node values can be negative, so it must start at negative infinity or at the level's first value.
- Reading the queue length inside the inner loop, which mixes levels together and collapses the answer.
- Not handling an empty tree, which must return an empty list rather than
[-inf]. - In the DFS variant, testing
depth > len(result)rather thandepth == len(result)to decide whether the level is new.
Full Solution — all languages
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def largestValues(self, root):
if not root: return []
from collections import deque
q = deque([root]); res = []
while q:
mx = float("-inf")
for _ in range(len(q)):
n = q.popleft(); mx = max(mx, n.val)
if n.left: q.append(n.left)
if n.right: q.append(n.right)
res.append(mx)
return resimport java.util.*;
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int v) {
val = v;
}
}
class Solution {
public int[] largestValues(TreeNode root) {
List<Integer> res = new ArrayList<>();
if (root == null) return new int[]{};
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
while (!q.isEmpty()) {
int sz = q.size();
int mx = Integer.MIN_VALUE;
for (int i = 0; i < sz; i++) {
TreeNode n = q.poll();
mx = Math.max(mx, n.val);
if (n.left != null) q.add(n.left);
if (n.right != null) q.add(n.right);
}
res.add(mx);
}
int[] out = new int[res.size()];
for (int i = 0; i < out.length; i++) out[i] = res.get(i);
return out;
}
}#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode(int v): val(v), left(nullptr), right(nullptr) {
}
};
class Solution {
public: vector<int> largestValues(TreeNode* root) {
vector<int> res;
if (!root) return res;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
int sz = q.size();
int mx = INT_MIN;
for (int i = 0; i < sz; i++) {
TreeNode* n = q.front();
q.pop();
mx = max(mx, n->val);
if (n->left) q.push(n->left);
if (n->right) q.push(n->right);
}
res.push_back(mx);
}
return res;
}
};/**
* Tree node shape: { val, left, right }
* @param {TreeNode} root
* @return {number[]}
*/ var largestValues = function(root) {
if (!root) return [];
let q = [root];
const res = [];
while (q.length) {
let mx = -Infinity;
const nq = [];
for (const n of q) {
mx = Math.max(mx, n.val);
if (n.left) nq.push(n.left);
if (n.right) nq.push(n.right);
}
res.push(mx);
q = nq;
}
return res;
};