- Leetcode: 1161 - Maximum level of sum of a binary tree
- Level: Medium
- Link
My approach
- Iterate through the tree with a bfs approach
- For each level, sum up the value of each leaf update to a dictionary
- Sort the dictionary by the value of each level, and return the smallest level with the biggest sum.
from collections import defaultdict
class Solution:
def maxLevelSum(self, root: TreeNode) -> int:
q = [(root, 1)]
cnt = 0
vals = defaultdict(int)
vals[1] = root.val
while q:
rt, level = q.pop(0)
if rt.left:
q.append((rt.left, level + 1))
vals[level + 1] += rt.left.val
if rt.right:
q.append((rt.right, level + 1))
vals[level + 1] += rt.right.val
sort_orders = sorted(vals.items(), key=lambda x: x[1], reverse=True)
return sort_orders[0][0]
'개발공부 > algorithm' 카테고리의 다른 글
[Leetcode][python] 973: K closest point to the origin (0) | 2021.04.28 |
---|---|
[Leetcode][python] 929: Unique email addresses (0) | 2021.04.28 |
[Leetcode][python] 257: binary tree paths - DFS (0) | 2021.04.27 |
[Leetcode][python] 733: flood fill - bfs (0) | 2021.04.25 |
[Leetcode][python] 690 - Employee importance - DFS (0) | 2021.04.25 |