Magicsheet logo

Find Largest Value in Each Tree Row

Medium
50%
Updated 6/1/2025

Find Largest Value in Each Tree Row

What is this problem about?

The Find Largest Value in Each Tree Row interview question asks you to find the maximum value in every level of a binary tree. You need to return a list where the ii-th element is the largest value in the ii-th row (depth) of the tree.

Why is this asked in interviews?

This is a standard assessment of Tree Traversal skills at companies like Apple, Microsoft, and Amazon. It tests whether you can adapt basic traversal algorithms to maintain state level-by-level. It evaluations your understanding of the Breadth-First Search (BFS) interview pattern and the Depth-First Search (DFS) interview pattern. It’s a clean, fundamental problem that checks for logical consistency.

Algorithmic pattern used

This problem is best solved using BFS (Level Order Traversal).

  1. Use a queue to process nodes.
  2. In each iteration, record the number of nodes currently in the queue (the current level's size).
  3. Iterate through that many nodes, updating a max_val for the current row.
  4. Add the children of these nodes to the queue for the next level.
  5. Alternatively, use DFS by passing the depth as an argument and updating a result list at result[depth].

Example explanation

Tree:

    1
   / 
  3   2
 / \   
5   3   9
  1. Row 0: [1]. Max = 1.
  2. Row 1: [3, 2]. Max = 3.
  3. Row 2: [5, 3, 9]. Max = 9. Result: [1, 3, 9].

Common mistakes candidates make

  • Initialization: Initializing the level max to 0 instead of the value of the first node or negative infinity. If all nodes are negative, 0 will be an incorrect answer.
  • Level Management: Failing to correctly identify the end of one row and the start of the next in BFS.
  • Recursion depth: Using DFS on a very deep tree without considering stack limits (though usually not an issue for typical interview constraints).

Interview preparation tip

For all "row-based" or "level-based" tree problems, BFS is usually the more robust choice because it naturally processes the tree in the order the result is requested. Practice the "Queue with Size" BFS template—it is the foundation for dozens of tree problems.

Similar Questions