You are given the root of a binary tree. For each level of the binary tree, find the largest value in each row and return them in a list.
Example:
Input:
1
/ \
3 2
/ \ \
5 3 9
Output: [1, 3, 9]
Note:
[0, 10^4]
.[-2^31, 2^31 - 1]
.We will use a breadth-first search (BFS) approach to traverse the tree level by level:
from collections import deque
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def largestValues(root: TreeNode) -> list:
if not root:
return []
result = []
queue = deque([root])
while queue:
level_size = len(queue)
max_value = float('-inf')
for _ in range(level_size):
node = queue.popleft()
max_value = max(max_value, node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
result.append(max_value)
return result
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?