-
[Leetcode] 1161. Maximum Level Sum of a Binary Tree개발/Leetcode 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
'개발 > Leetcode' 카테고리의 다른 글
Leetcode 125. Valid Palindrome (0) 2023.06.24 Leetcode 1232. Check If It Is a Straight Line (0) 2023.06.24 Leetcode 121. Best Time to Buy and Sell Stock (0) 2023.06.24 Leetcode 217. Contains Duplicate (0) 2023.06.24 Leetcode 714. Best Time to Buy and Sell Stock with Transaction Fee (0) 2023.06.22