Maximum Level Sum of a Binary Tree — LeetCode 1161 Python Solution
- Problem
- #1161
- Pattern
- Tree Traversal
- Reading time
- 5 min
- Source
- leetcode.com
The problem
Given the root of a binary tree, the level of its root is 1, the level of its children is 2, and so on. Return the smallest level x such that the sum of all the values of nodes at level x is maximal.
Example
- Input
- root = [1,7,0,7,-8,null,null]
- Output
- 2
- Explanation
- Level 1 sum = 1.
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 maxLevelSum(self, root: Optional[TreeNode]) -> int:
q = deque([root])
mx = -inf
i = 0
while q:
i += 1
s = 0
for _ in range(len(q)):
node = q.popleft()
s += node.val
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
if mx < s:
mx = s
ans = i
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n), where n is the number of nodes in the binary tree auxiliary |
Pattern: Tree Traversal
Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 1161. Maximum Level Sum of a Binary Tree 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
On a study list
This problem is on LeetCode 75.
Frequently asked questions
- How hard is LeetCode 1161. Maximum Level Sum of a Binary Tree?
- LeetCode 1161. Maximum Level Sum of a Binary Tree is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1161. Maximum Level Sum of a Binary Tree?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 1161. Maximum Level Sum of a Binary Tree?
- The Python solution on this page uses O(n), where n is the number of nodes in the binary tree auxiliary space.
- What topics does LeetCode 1161. Maximum Level Sum of a Binary Tree cover?
- LeetCode 1161. Maximum Level Sum of a Binary Tree is tagged Tree, Depth-First Search, Breadth-First Search and Binary Tree on LeetCode.