Find Largest Value in Each Tree Row (LeetCode 515): Solution and Explanation

Medium
Tree
Depth First Search
Breadth First Search
Binary Tree

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

  1. If the root is null return an empty list. Otherwise set level = [root].
  2. While level is not empty, set best to the value of its first node and create an empty next list.
  3. For every node in level, update best = max(best, node.val) and append its non-null children to next.
  4. Append best to the result and replace level with next.
  5. Return the result once a level comes back empty.

Step-by-step example

root = [1,3,2,5,3,null,9]
  1. Row 0 is [1]. best starts at 1 and nothing beats it. Children 3 and 2 are queued. result = [1].
  2. Row 1 is [3, 2]. best starts at 3; 2 is smaller. Children 5, 3 and 9 are queued. result = [1, 3].
  3. Row 2 is [5, 3, 9]. best starts at 5, 3 is smaller, 9 replaces it. No children. result = [1, 3, 9].
  4. 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 result
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Every node is placed in exactly one row and compared once.

Space

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.