Find Largest Value in Each Tree Row - Problem

Given the root of a binary tree, return an array of the largest value in each row of the tree (0-indexed).

Each row represents all nodes at the same level/depth in the tree. The result should contain the maximum value found at each level, starting from the root level (level 0) down to the deepest level.

Example: For a tree with root value 1, left child 3, and right child 2, where 3 has children 5 and 3, and 2 has child 9, the result would be [1, 3, 9] representing the maximum values at levels 0, 1, and 2 respectively.

Input & Output

Example 1 — Standard Binary Tree
$ Input: root = [1,3,2,5,3,null,9]
Output: [1,3,9]
💡 Note: Level 0: Only node 1, max = 1. Level 1: Nodes 3 and 2, max = 3. Level 2: Nodes 5, 3, and 9, max = 9.
Example 2 — Single Node Tree
$ Input: root = [1]
Output: [1]
💡 Note: Tree has only root node at level 0 with value 1.
Example 3 — Left-skewed Tree
$ Input: root = [5,4,null,3,null,null,null,2]
Output: [5,4,3,2]
💡 Note: Each level has one node: 5 at level 0, 4 at level 1, 3 at level 2, 2 at level 3.

Constraints

  • The number of nodes in the tree will be in the range [1, 104].
  • -231 ≤ Node.val ≤ 231 - 1

Visualization

Tap to expand
Find Largest Value in Each Tree RowInput: Tree Structure132539Process: Level-by-Level AnalysisLevel 0: [1] → max = 1Level 1: [3,2] → max = 3Level 2: [5,3,9] → max = 9Output: Result Array139Index: 0 1 2Result: [1, 3, 9]
Understanding the Visualization
1
Input Tree
Binary tree with nodes at different levels
2
Level Analysis
Identify nodes at each level and find maximum
3
Result Array
Collect maximum values from each level
Key Takeaway
🎯 Key Insight: Use level-order traversal to naturally group nodes by tree rows, then track maximum at each level
Asked in
Amazon 35 Facebook 28 Microsoft 22 Google 18
127.0K Views
Medium Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen