Find Largest Value In Each Tree Row Problem
Description
LeetCode Problem 515.
Given the root of a binary tree, return an array of the largest value in each row of the tree (0-indexed).
Example 1:
Input: root = [1,3,2,5,3,null,9]
Output: [1,3,9]
Example 2:
Input: root = [1,2,3]
Output: [1,3]
Example 3:
Input: root = [1]
Output: [1]
Example 4:
Input: root = [1,null,2]
Output: [1,2]
Example 5:
Input: root = []
Output: []
Constraints:
- The number of nodes in the tree will be in the range [0, 10^4].
- -2^31 <= Node.val <= 2^31 - 1
Solution
Approach: Breadth-First Search Row by Row
A breadth-first search visits the tree one row at a time, so we can take the maximum of each row while we build the next one.
- If the tree is empty, return an empty list.
- Start with
row = [root]. - While
rowis not empty:- walk through its nodes, keeping the largest value seen, and collect their children (left, then right) into
nextRow; - append the largest value to the answer and continue with
row = nextRow.
- walk through its nodes, keeping the largest value seen, and collect their children (left, then right) into
Example 1, [1,3,2,5,3,null,9]: the rows are [1], [3, 2] and [5, 3, 9], so the answer is [1, 3, 9].
The detail to watch is the starting value of the maximum. Node values go down to -231, so starting at 0 (or any fixed guess) gives a wrong answer on a row of negative numbers. Start from the value of the row's first node instead.
Complexity: O(n) time and O(w) space, where n is the number of nodes and w is the largest number of nodes in one row.
class Solution:
def largestValues(self, root: Optional[TreeNode]) -> List[int]:
answer = []
if root is None:
return answer
row = [root]
while row:
largest = row[0].val
# The children of this row, from left to right, form the next row.
next_row = []
for node in row:
largest = max(largest, node.val)
if node.left is not None:
next_row.append(node.left)
if node.right is not None:
next_row.append(node.right)
answer.append(largest)
row = next_row
return answer