개발/Leetcode
[Leetcode] 1161. Maximum Level Sum of a Binary Tree
지산동고라니
2023. 6. 15. 10:30
https://leetcode.com/problems/maximum-level-sum-of-a-binary-tree/description/
Maximum Level Sum of a Binary Tree - LeetCode
Can you solve this real interview question? Maximum Level Sum of a Binary Tree - 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 node
leetcode.com
문제
바이너리 트리인 root가 주어진다. 이 트리의 루트는 레벨 1이며 그 자식은 레벨 2와 같은 순서대로 레벨이 주어진다.
level x에 있는 노드들의 합이 가장 큰 최소 레벨의 값을 반환하라
제출한 답
class Solution:
def maxLevelSum(self, root: Optional[TreeNode]) -> int:
m = {}
def r(level, node):
if node is None:
return
if level not in m:
m[level] = []
m[level] += [node.val]
if node.left is None and node.right is None:
return
if node.left is not None:
r(level + 1, node.left)
if node.right is not None:
r(level + 1, node.right)
r(1, root)
result = list(map(lambda x: sum(m[x]), m.keys()))
return result.index(max(result)) + 1