Problem
Given theroot of a binary tree, return an array of the largest value in each row of the tree (0-indexed).
Examples
Constraints
- The number of nodes in the tree will be in the range
[0, 10^4]. -2^31 <= Node.val <= 2^31 - 1
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 515 with 15 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 515 # by problem number
lcpy gen -s find_largest_value_in_each_tree_row # by problem name
root of a binary tree, return an array of the largest value in each row of the tree (0-indexed).
Input: root = [1,3,2,5,3,null,9]
Output: [1,3,9]
Input: root = [1,2,3]
Output: [1,3]
[0, 10^4].-2^31 <= Node.val <= 2^31 - 1from collections import deque
from leetcode_py import TreeNode
class Solution:
# Time: O(n)
# Space: O(n)
def largest_values(self, root: TreeNode[int] | None) -> list[int]:
if root is None:
return []
result: list[int] = []
queue: deque[TreeNode[int]] = deque([root])
while queue:
result.append(max(node.val for node in queue))
for _ in range(len(queue)):
node = queue.popleft()
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return result
| Time | Space |
|---|---|
| O(n) | O(n) |