Skip to content

Commit ec03050

Browse files
committed
Oct 22
1 parent 270d701 commit ec03050

File tree

2 files changed

+55
-2
lines changed

2 files changed

+55
-2
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
from collections import deque
2+
from heapq import heappop, heappush
3+
from typing import Optional
4+
5+
6+
# Definition for a binary tree node.
7+
class TreeNode:
8+
def __init__(self, val=0, left=None, right=None):
9+
self.val = val
10+
self.left = left
11+
self.right = right
12+
13+
14+
class Solution:
15+
def kthLargestLevelSum(self, root: Optional[TreeNode], k: int) -> int:
16+
heap = []
17+
queue = deque([root])
18+
while queue:
19+
level_sum = 0
20+
next_level = []
21+
while queue:
22+
node = queue.popleft()
23+
level_sum += node.val
24+
next_level.extend(filter(None, (node.left, node.right)))
25+
heappush(heap, level_sum)
26+
if len(heap) > k:
27+
heappop(heap)
28+
queue = deque(next_level)
29+
return heap[0] if len(heap) == k else -1
30+
31+
32+
def main():
33+
root = TreeNode(5)
34+
root.left = TreeNode(8)
35+
root.right = TreeNode(9)
36+
root.left.left = TreeNode(2)
37+
root.left.right = TreeNode(1)
38+
root.right.left = TreeNode(3)
39+
root.right.right = TreeNode(7)
40+
root.left.left.left = TreeNode(4)
41+
root.left.left.right = TreeNode(6)
42+
k = 2
43+
assert Solution().kthLargestLevelSum(root, k) == 13
44+
45+
root = TreeNode(1)
46+
root.left = TreeNode(2)
47+
root.left.left = TreeNode(3)
48+
k = 1
49+
assert Solution().kthLargestLevelSum(root, k) == 3
50+
51+
52+
if __name__ == '__main__':
53+
main()

2024-10-October-LeetCoding-Challenge/README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
| October 19 | [1545. Find Kth Bit in Nth Binary String](https://leetcode.com/problems/find-kth-bit-in-nth-binary-string/) | Medium | Unsolved |
2525
| October 20 | [1106. Parsing A Boolean Expression](https://leetcode.com/problems/parsing-a-boolean-expression/) | Hard | Solved |
2626
| October 21 | [1593. Split a String Into the Max Number of Unique Substrings](https://leetcode.com/problems/split-a-string-into-the-max-number-of-unique-substrings/) | Medium | Solved |
27-
| October 22 | []() | | |
27+
| October 22 | [2583. Kth Largest Sum in a Binary Tree](https://leetcode.com/problems/kth-largest-sum-in-a-binary-tree/) | Medium | Solved |
2828
| October 23 | []() | | |
2929
| October 24 | []() | | |
3030
| October 25 | []() | | |
@@ -40,5 +40,5 @@
4040
| Level | Problems | Solved | Unsolved |
4141
| --- | --- | --- | --- |
4242
| Easy | 2 | 2 | 0 |
43-
| Medium | 17 | 9 | 8 |
43+
| Medium | 18 | 10 | 8 |
4444
| Hard | 2 | 1 | 1 |

0 commit comments

Comments
 (0)