Re: [闲聊] 每日leetcode

楼主: dont   2024-10-22 21:02:24
2583. Kth Largest Sum in a Binary Tree
## 思路
BFS计算每层的总和, 丢到 k-size的min-heap
## Code
```python
# 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 kthLargestLevelSum(self, root: Optional[TreeNode], k: int) -> int:
heap = []
queue = deque([root])
while queue:
curr = 0
for _ in range(len(queue)):
node = queue.popleft()
curr += node.val
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
heapq.heappush(heap, curr)
if len(heap) > k:
heapq.heappop(heap)
return -1 if len(heap) < k else heap[0]
```
作者: sustainer123 (caster)   2024-10-22 21:05:00
大师 教我

Links booklink

Contact Us: admin [ a t ] ucptt.com