15% off all plans & roadmaps Use code
See plansFind Largest Value in Each Tree Row
- LeetCode 515
- Medium
- Tree Traversal Patterns (DFS & BFS)
- Level Order Traversal
Updated
TL;DR: Return the largest value in every row of a binary tree. A breadth-first walk that handles one row per round reads each node once and gives the answer in O(n) time.
Problem
You are given the root of a binary tree. Return an array that holds the largest value in each row of the tree. Rows are 0-indexed, so the first entry describes the root row.
Example 1
Input: root = [1,3,2,5,3,null,9] Output: [1,3,9]
Example 2
Input: root = [1,2,3] Output: [1,3]
Constraints
- The number of nodes in the tree is in the range
[0, 10^4]. -2^31 <= Node.val <= 2^31 - 1
Constraints that matter
- A limit of 10^4 nodes rules out checking every node for every row when the tree is a long chain. That work can reach about 10^8 steps, which is too slow in the worst case, so each node should be read once.
- Values go down to -2^31, so a starting value of 0 for the row maximum gives wrong answers. Start from a real value in the row, or from the smallest possible int, and both work because every row has at least one node.
- The tree can be empty, so
rootcan be null. Check for that before readingroot.val. - Output length equals the number of rows, and that is at most 10^4. The answer needs one stored value per row, not one per node.
Hints
Hint 1
The problem asks for one answer per row, so the row is the unit of work.
Hint 2
A beginner treats each row as its own question.
Solution
Intuition
The problem asks for one answer per row, so the row is the unit of work. A row is a depth level. Level order traversal, which is breadth-first search with a queue, visits the tree one row at a time. Reach for this pattern whenever a question asks for something per level.
Picture a line of people waiting to board a bus, grouped by seat row. The queue is the line, the row size is how many people are in the front group, and you board exactly that group before calling the next one.
What to notice: a queue returns items in the order they were added. Children join the back of the queue, so every node in the current row sits ahead of every node in the next row. If you read the queue size at the start of a round, you know exactly how many nodes belong to the current row.
Each round pops that many nodes, records their maximum, and pushes their children. When the round ends, the queue holds only the next row. Each node is pushed once and popped once, so one pass over the tree produces every row's answer.
Worked example
Input: root = [1, 3, 2, 5, 3, null, 9] Output: [1, 3, 9] Explanation: The tree has three rows: [1], then [3, 2], then [5, 3, 9]. The largest value in each row is 1, 3 and 9.
Approach 1: Brute force: rescan the tree for each row
A beginner treats each row as its own question. To answer for row 1, walk the whole tree and keep the largest value at depth 1. Repeat the full walk for row 2, row 3, and so on. Stop when a walk finds no node at the next depth.
This works because each walk looks at every node, so no row is missed. It is slow because a walk for row 3 reads the root and row 2 nodes and throws them away.
Steps
- Set
rowto 1 and start an empty result list. Rows are numbered from 1 here, so the root row is row 1. - Walk the whole tree with an explicit stack. Store each node with its depth, where the root has depth 1.
- For each node whose depth equals
row, keep the largest value seen. Track whether any node matched. - If no node matched, stop and return the result.
- Otherwise append the largest value to the result, add 1 to
row, and repeat from the walk.
Dry run
The tree has 6 nodes and height 3.
- Row 1: the walk visits all 6 nodes. Only the root sits at depth 1, so the best value is 1.
- Row 2: the walk visits all 6 nodes again. Nodes 3 and 2 sit at depth 2, so the best value is 3.
- Row 3: the walk visits all 6 nodes once more. Nodes 5, 3 and 9 sit at depth 3, so the best value is 9.
- Row 4: the walk visits all 6 nodes and finds nothing, so the loop stops.
The result is [1, 3, 9].
Complexity
| Time | O(n * H) |
|---|---|
| Space | O(H) |
Here n is the number of nodes and H is the height. One walk pushes and pops every node once, so it costs O(n). The loop runs once per row plus one final empty walk, so the total is O(n * (H + 1)), which is O(n * H). For a chain, H equals n, so the cost is O(n^2). The stack holds at most about two entries per level on the current path, so the space is O(H).
PythonTested in our runner
from typing import List, Optional
class Solution:
def largestValues(self, root: Optional[TreeNode]) -> List[int]:
result = []
if root is None:
return result
row = 1 # rows are numbered from 1, so the root row is row 1
while True:
best = None # largest value seen at this depth
stack = [(root, 1)] # explicit stack, so deep trees avoid recursion limits
while stack:
node, depth = stack.pop()
if depth == row and (best is None or node.val > best):
best = node.val
if node.left:
stack.append((node.left, depth + 1))
if node.right:
stack.append((node.right, depth + 1))
if best is None: # no node sits at this depth, so the rows are done
return result
result.append(best)
row += 1The Level Order Traversal infographic is part of Pro
A one-page visual of the pattern: when it applies, the steps and the invariant to keep.
Unlock the infographicSolution pattern
Level Order Traversal
Approach 2: Level order BFS with a queueOptimalLevel Order Traversal
What is slow in the brute force is the repeated walk. Each scan touches every node, but it only uses the nodes in one row, so most of the work is wasted. The insight that fixes it is that a queue visits nodes row by row. The queue size at the start of a round is exactly the size of the current row, so one pass can answer every row.
Keep track of where the current row ends while you work. Pop exactly that many nodes, track their maximum, and push their children behind them. Then append the maximum and start the next round.
Steps
- If the root is null, return an empty list.
- Put the root in a queue.
- While the queue is not empty, save its current size as the row size.
- Set the row maximum to the first value in the row, or to the smallest int.
- Pop exactly row-size nodes. For each one, update the row maximum and push any non-null children.
- Append the row maximum to the result and start the next round.
- Return the result when the queue is empty.
Dry run
Start with queue [1] and result [].
| Step | Action | Queue after step | Row max | Result |
|---|---|---|---|---|
| 1 | Row 0 has size 1. Pop 1, push 3 and 2. Row ends. | [3, 2] | 1 | [1] |
| 2 | Row 1 has size 2. Pop 3, push 5 and 3. | [2, 5, 3] | 3 | [1] |
| 3 | Pop 2, push 9 (left is null). Row ends. | [5, 3, 9] | 3 | [1, 3] |
| 4 | Row 2 has size 3. Pop 5, no children. | [3, 9] | 5 | [1, 3] |
| 5 | Pop 3, no children. | [9] | 5 | [1, 3] |
| 6 | Pop 9. Row ends. | [] | 9 | [1, 3, 9] |
The queue is empty and the result is [1, 3, 9], which matches the example.
Complexity
| Time | O(n) |
|---|---|
| Space | O(n) |
Here n is the number of nodes. Each node is pushed once by its parent and popped once, so the loop body runs n times with constant work each, which gives O(n). The queue holds nodes from at most two adjacent rows at once, so its size is bounded by the width of those rows. That width is at most n, so the space is O(n) in the worst case. A perfect tree keeps about n/2 nodes in its last row, so that bound is reached in practice.
PythonTested in our runner
from collections import deque
from typing import List, Optional
class Solution:
def largestValues(self, root: Optional[TreeNode]) -> List[int]:
result = []
if root is None:
return result
queue = deque([root])
while queue:
row_size = len(queue) # nodes in the current row, read before children are added
row_max = float('-inf')
for _ in range(row_size):
node = queue.popleft()
row_max = max(row_max, node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
result.append(row_max)
return resultCommon mistakes
row_max = 0as the starting value. A row of only negative numbers, such as [-5, -2], then reports 0. Start from the first value in the row or from the smallest int.for (int i = 0; i < queue.size(); i++)in Java or C++. The queue grows during the loop, so the loop eats into the next row. Save the size in a variable before the loop starts.queue.offer(node.left)without a null check. A null goes into the queue, and the next pop dereferences it and crashes. Check each child before pushing it.result.add(rowMax)inside the inner loop. That adds one entry per node instead of one per row. Append after the inner loop closes.- Reading
root.valbefore checkingroot == null. An empty tree is valid input and should return an empty array. if (best == Integer.MIN_VALUE) break;as the stop test in the brute force. A real node with value -2^31 would stop the loop early. Track a separate found flag instead.
Edge cases
- Empty tree (root is null): return an empty array.
- Single node with value -7: return [-7].
- All negative values, such as root = [-5, -2, -9]: rows are [-5] and [-2, -9], so return [-5, -2].
- Node value -2147483648 (the smallest 32-bit int): the row maximum is that value, so the answer is [-2147483648].
- A chain of 10^4 nodes: the output has 10^4 entries. Recursive DFS can overflow the stack in Python, so use the queue or an explicit stack.
- Duplicate values in one row, such as root = [2, 2, 2]: the row maximum is 2, and the output is [2, 2].
- A tree with a missing left child, such as root = [1, null, 2]: rows are [1] and [2], so return [1, 2].
Follow-ups interviewers ask
Follow-ups are part of Pro
The questions interviewers ask after you solve Find Largest Value in Each Tree Row, with how to answer them.
Unlock the follow-upsFind Largest Value in Each Tree Row FAQ
What is the time complexity of Find Largest Value in Each Tree Row?
The optimal BFS solution runs in O(n) time, where n is the number of nodes, because each node is pushed and popped once. The brute force that rescans the tree for each row runs in O(n * H), where H is the height. The O(n) bound is the one to give in an interview.
Why use level order traversal for Find Largest Value in Each Tree Row?
The output needs one answer per row, and a row is a depth level. A queue visits nodes level by level, so the queue size at the start of a round gives the row boundary. That lets you compute each row's maximum in one pass.
Can Find Largest Value in Each Tree Row be solved in O(1) extra space?
Not with the standard queue or stack. A BFS queue can hold about n/2 nodes in a perfect tree, and a DFS stack can hold H nodes in a chain. Morris-style traversals avoid the stack but are error-prone when you also need depth, so interviews usually accept O(n) or O(H).
Why does the Python solution use deque instead of a list?
A deque removes from the front in O(1) time. Calling list.pop(0) shifts every remaining element, which makes each removal cost O(n). With 10^4 nodes that difference adds up.
Can I solve this problem with recursion in Python?
You can, but the default recursion limit is about 1000 frames. A chain of 10^4 nodes exceeds that limit and raises a RecursionError. Use the queue or an explicit stack for this problem.
Asked at
See which companies ask this — Pro
Related problems
- Binary Tree Level Order Traversal · same technique: Level Order Traversal
- Binary Tree Right Side View · same technique: Level Order Traversal
- Binary Tree Zigzag Level Order Traversal · same technique: Level Order Traversal
- Maximum Level Sum of a Binary Tree · same technique: Level Order Traversal
- Binary Tree Maximum Path Sum · next harder, same pattern
- Validate Binary Search Tree · same pattern: Tree Traversal Patterns (DFS & BFS)
- Construct Binary Tree from Preorder and Inorder Traversal · same pattern: Tree Traversal Patterns (DFS & BFS)
- Lowest Common Ancestor of a Binary Search Tree · same pattern: Tree Traversal Patterns (DFS & BFS)
- Kth Smallest Element in a BST · same pattern: Tree Traversal Patterns (DFS & BFS)
- Count Good Nodes in Binary Tree · same pattern: Tree Traversal Patterns (DFS & BFS)