#515

Find Largest Value in Each Tree Row

Medium
TreeDepth-First SearchBreadth-First SearchBinary TreeBreadth-First SearchTree Traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a breadth-first search (BFS) approach to traverse the tree level by level while keeping track of the maximum value at each level. This is efficient and avoids unnecessary repeated traversals.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a queue with the root node.
  2. 2Step 2: While the queue is not empty, determine the number of nodes at the current level.
  3. 3Step 3: For each node, update the maximum value for the current level and enqueue its children.
  4. 4Step 4: After processing all nodes at the current level, add the maximum value to the result list.
solution.py20 lines
1# Full working Python code
2from collections import deque
3
4def largestValues(root):
5    if not root:
6        return []
7    result = []
8    queue = deque([root])
9    while queue:
10        level_size = len(queue)
11        max_value = float('-inf')
12        for _ in range(level_size):
13            node = queue.popleft()
14            max_value = max(max_value, node.val)
15            if node.left:
16                queue.append(node.left)
17            if node.right:
18                queue.append(node.right)
19        result.append(max_value)
20    return result

Complexity note: The complexity is O(n) because we visit each node exactly once, and O(n) space is used for the queue in the worst case (a complete binary tree).

  • 1Using BFS allows us to efficiently traverse the tree level by level.
  • 2Tracking the maximum value at each level is crucial for the solution.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.