Content-Length: 288879 | pFad | http://github.com/ramtanniru/Leetcode/commit/d4508b59cb79d61c0042fa68a21bcb8fbfe689c2

C4 2583 · ramtanniru/Leetcode@d4508b5 · GitHub
Skip to content

Commit d4508b5

Browse files
committed
2583
1 parent 1088b63 commit d4508b5

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

Oct-22-24.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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+
if not root:
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]

0 commit comments

Comments
 (0)








ApplySandwichStrip

pFad - (p)hone/(F)rame/(a)nonymizer/(d)eclutterfier!      Saves Data!


--- a PPN by Garber Painting Akron. With Image Size Reduction included!

Fetched URL: http://github.com/ramtanniru/Leetcode/commit/d4508b59cb79d61c0042fa68a21bcb8fbfe689c2

Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy