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 Row INPUT Binary Tree Structure 1 Level 0 3 2 Level 1 5 3 9 Level 2 Input Array Representation: [1, 3, 2, 5, 3, null, 9] ALGORITHM (BFS) 1 Initialize Queue Add root to queue Q: [1] 2 Process Level 0 max(1) = 1 result: [1] 3 Process Level 1 max(3, 2) = 3 result: [1,3] 4 Process Level 2 max(5, 3, 9) = 9 result: [1,3,9] BFS traverses level by level Level 0: [1] --> max = 1 Level 1: [3,2] --> max = 3 Level 2: [5,3,9] --> max = 9 FINAL RESULT Maximum values highlighted 1 MAX 3 MAX 2 5 3 9 MAX Output Array: [1, 3, 9] OK - Verified! Key Insight: BFS (Breadth-First Search) naturally processes nodes level by level. By using a queue, we process all nodes at the current level before moving to the next. Track the maximum value at each level iteration. Time: O(n) - visit each node once | Space: O(w) - max width of tree for queue storage TutorialsPoint - Find Largest Value in Each Tree Row | BFS Approach
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