Find Largest Value in Each Tree Row

Medium

Topics
TreeBFS

Given the root of a binary tree, return an array containing the largest value in each row (level), ordered from the top row to the bottom row.

Example 1

533129
largest on its level
One maximum per level, top down: [1, 3, 9].
Tree given in level-order (breadth-first); null marks a missing child.
Input:  root = [1,3,2,5,3,null,9]
Output: [1,3,9]

Example 2

213
largest on its level
Input:  root = [1,2,3]
Output: [1,3]

Constraints

  • 0 <= number of nodes <= 10^4
  • -2^31 <= Node.val <= 2^31 - 1
Editorial — intuition, approach, complexity and pitfalls

Intuition

One value per level, so process the tree a level at a time and take each level's maximum. The level-order BFS pattern again: capture the queue's length before the inner loop, and that count is exactly the level's width.

A DFS also works — carry the depth, and for each node either append its value (if this depth is new) or fold it into the existing entry with max. Same O(n) time, O(h) space instead of O(w), which is the better trade on a wide shallow tree.

Approach

  1. Return empty for an empty tree.
  2. For each level, scan its nodes tracking the maximum and enqueuing children.
  3. Append the maximum.

Dry Run

tree        1
           / \
          3   2
         / \   \
        5   3   9

level 0  [1]        max 1
level 1  [3,2]      max 3
level 2  [5,3,9]    max 9

answer [1,3,9]

Complexity

  • Time — O(n): each node visited once.
  • Space — O(w): the queue holds one level, up to about n/2 on a complete tree. The DFS variant is O(h).

Common Pitfalls

  • Initialising the per-level maximum to 0. Node values can be negative, so it must start at negative infinity or at the level's first value.
  • Reading the queue length inside the inner loop, which mixes levels together and collapses the answer.
  • Not handling an empty tree, which must return an empty list rather than [-inf].
  • In the DFS variant, testing depth > len(result) rather than depth == len(result) to decide whether the level is new.

Full Solution — all languages

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def largestValues(self, root):
        if not root: return []
        from collections import deque
        q = deque([root]); res = []
        while q:
            mx = float("-inf")
            for _ in range(len(q)):
                n = q.popleft(); mx = max(mx, n.val)
                if n.left: q.append(n.left)
                if n.right: q.append(n.right)
            res.append(mx)
        return res
SensAI
Beta
Tap the mic to stop voice mode