Find Largest Value in Each Tree Row (LeetCode 515): Solution and Explanation
Given a binary tree, return the largest value found on each row, from the top row down. An empty tree gives an empty list.
Intuition
The question is about rows, so the natural tool is a traversal that already works row by row: breadth-first search.
If the current row sits in a list, its maximum is a plain running max over that list. While scanning it, the children of each node form the next row, so one pass both answers this row and sets up the next one.
The only trap is the starting value of the running max. Values go down to -2^31, so seeding with 0 would report 0 for an all-negative row. Seeding with the row's first value avoids that.
Approach: Level-by-level BFS
- If the root is null return an empty list. Otherwise set
level = [root]. - While
levelis not empty, setbestto the value of its first node and create an emptynextlist. - For every node in
level, updatebest = max(best, node.val)and append its non-null children tonext. - Append
bestto the result and replacelevelwithnext. - Return the result once a level comes back empty.
Step-by-step example
root = [1,3,2,5,3,null,9]
- Row 0 is [1]. best starts at 1 and nothing beats it. Children 3 and 2 are queued. result = [1].
- Row 1 is [3, 2]. best starts at 3; 2 is smaller. Children 5, 3 and 9 are queued. result = [1, 3].
- Row 2 is [5, 3, 9]. best starts at 5, 3 is smaller, 9 replaces it. No children. result = [1, 3, 9].
- The next row is empty, so return [1, 3, 9].
Code: Python, Java, C++
1class Solution:
2 def largestValues(self, root: Optional[TreeNode]) -> List[int]:
3 result = []
4 level = [root] if root else []
5 while level:
6 best = level[0].val
7 nxt = []
8 for node in level:
9 best = max(best, node.val)
10 if node.left:
11 nxt.append(node.left)
12 if node.right:
13 nxt.append(node.right)
14 result.append(best)
15 level = nxt
16 return result1class Solution {
2 public List<Integer> largestValues(TreeNode root) {
3 List<Integer> result = new ArrayList<>();
4 List<TreeNode> level = new ArrayList<>();
5 if (root != null) level.add(root);
6 while (!level.isEmpty()) {
7 int best = level.get(0).val;
8 List<TreeNode> next = new ArrayList<>();
9 for (TreeNode node : level) {
10 best = Math.max(best, node.val);
11 if (node.left != null) next.add(node.left);
12 if (node.right != null) next.add(node.right);
13 }
14 result.add(best);
15 level = next;
16 }
17 return result;
18 }
19}1class Solution {
2public:
3 vector<int> largestValues(TreeNode* root) {
4 vector<int> result;
5 vector<TreeNode*> level;
6 if (root) level.push_back(root);
7 while (!level.empty()) {
8 int best = level[0]->val;
9 vector<TreeNode*> next;
10 for (TreeNode* node : level) {
11 best = max(best, node->val);
12 if (node->left) next.push_back(node->left);
13 if (node->right) next.push_back(node->right);
14 }
15 result.push_back(best);
16 level = next;
17 }
18 return result;
19 }
20};Time and space complexity
O(n)
Every node is placed in exactly one row and compared once.
O(w)
Only the current row and the next one are stored, so memory is bounded by the widest row w (up to about n/2 for a full tree).
Other approaches
DFS with a depth index (time O(n), space O(h))
Recurse with the current depth. If depth equals the result length, append the value; otherwise take the max with result[depth]. It uses the recursion stack instead of a queue.
Single queue with a size snapshot (time O(n), space O(w))
Use one deque and read its length at the start of each row, popping exactly that many nodes. Same idea as two lists, slightly less allocation.
Common mistakes
- Seeding the running max with 0 or a small constant instead of the first value in the row, which breaks all-negative rows.
- In C++ or Java, seeding with INT_MIN is fine, but adding to it or using it as a sentinel in arithmetic can overflow.
- Forgetting the empty tree, which must return an empty list rather than [0] or null.
- Mixing rows by pushing children onto the same queue without remembering where the current row ends.
Frequently asked questions
Is BFS or DFS better here?
Both are O(n) time. BFS uses memory proportional to the widest row; DFS uses memory proportional to the height. For a balanced tree DFS uses less, for a long chain BFS uses less.
Why not start best at 0?
Node values can be negative down to -2^31. A row like [-5, -3] would wrongly report 0. Starting from the first value in the row is always safe.
What does the result look like for a skewed tree?
Each row has one node, so the result is simply the node values from top to bottom.