Content-Length: 288879 | pFad | http://github.com/ramtanniru/Leetcode/commit/d4508b59cb79d61c0042fa68a21bcb8fbfe689c2
We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 1088b63 commit d4508b5Copy full SHA for d4508b5
Oct-22-24.py
@@ -0,0 +1,26 @@
1
+class Solution:
2
+ def kthLargestLevelSum(self, root: Optional[TreeNode], k: int) -> int:
3
+ def depth(root):
4
+ if not root:
5
+ return 0
6
+ return 1+max(depth(root.left),depth(root.right))
7
+ def dfs(root,l):
8
+ nonlocal levels
9
10
+ return
11
+ levels[l].append(root.val)
12
+ dfs(root.left,l+1)
13
+ dfs(root.right,l+1)
14
+ heap = []
15
+ height = depth(root)
16
+ if height<k: return -1
17
+ levels = [[] for i in range(height)]
18
+ dfs(root,0)
19
+ for l in levels[:k]:
20
+ heapq.heappush(heap,sum(l))
21
+ for l in levels[k:]:
22
+ s = sum(l)
23
+ if heap[0]<s:
24
+ heapq.heappop(heap)
25
+ heapq.heappush(heap,s)
26
+ return heap[0]
Fetched URL: http://github.com/ramtanniru/Leetcode/commit/d4508b59cb79d61c0042fa68a21bcb8fbfe689c2
Alternative Proxies:
Alternative Proxy
pFad Proxy
pFad v3 Proxy
pFad v4 Proxy
0 commit comments