MediumNo. 0515
Find Largest Value in Each Tree Row — LeetCode 515 Python Solution
- Pattern
- Tree Traversal
- Topics
- Tree, Depth-First Search, Breadth-First Search, Binary Tree
- Reading time
- 4 min
- Source
- leetcode.com
The problem
Given the root of a binary tree, return an array of the largest value in each row of the tree (0-indexed).
Example
- Input
- root = [1,3,2,5,3,null,9]
- Output
- [1,3,9]
Python solution
# 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
class Solution:
def largestValues(self, root: Optional[TreeNode]) -> List[int]:
ans = []
if root is None:
return ans
q = deque([root])
while q:
x = -inf
for _ in range(len(q)):
node = q.popleft()
x = max(x, node.val)
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
ans.append(x)
return ansComplexity
- Time
- O(n)
- Space · auxiliary
- O(n)
Pattern: Tree Traversal
Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 515. Find Largest Value in Each Tree Row is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.
The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0513 | Find Bottom Left Tree Value | Medium |
| 0100 | Same Tree | Easy |
| 0101 | Symmetric Tree | Easy |
| 0104 | Maximum Depth of Binary Tree | Easy |
| 0111 | Minimum Depth of Binary Tree | Easy |
| 0112 | Path Sum | Easy |
Frequently asked questions
- How hard is LeetCode 515. Find Largest Value in Each Tree Row?
LeetCode 515. Find Largest Value in Each Tree Row is rated Medium on LeetCode.
- What is the time complexity of LeetCode 515. Find Largest Value in Each Tree Row?
The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 515. Find Largest Value in Each Tree Row?
The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 515. Find Largest Value in Each Tree Row cover?
LeetCode 515. Find Largest Value in Each Tree Row is tagged Tree, Depth-First Search, Breadth-First Search and Binary Tree on LeetCode.