MCPcopy Create free account
hub / github.com/Tiwarishashwat/InterviewCodes / kthLargestLevelSum

Method kthLargestLevelSum

KthLargestSumInABinaryTree.java:17–48  ·  view source on GitHub ↗
(TreeNode root, int k)

Source from the content-addressed store, hash-verified

15 */
16class Solution {
17 public long kthLargestLevelSum(TreeNode root, int k) {
18
19 // BF
20 // max heap
21 //bfs - min heap.
22 Queue<TreeNode> queue = new LinkedList<>();
23 PriorityQueue<Long> pq = new PriorityQueue<>();
24 queue.offer(root);
25 while(!queue.isEmpty()){
26 int size = queue.size();
27 long sum = 0l;
28 for(int i=0;i<size;i++){
29 TreeNode node = queue.poll();
30 sum += node.val;
31 if(node.left!=null){
32 queue.offer(node.left);
33 }
34 if(node.right!=null){
35 queue.offer(node.right);
36 }
37 }
38 pq.offer(sum);
39 if(pq.size()>k){
40 pq.poll();
41 }
42 }
43 //-1 case
44 if(pq.size()<k){
45 return -1;
46 }
47 return pq.peek();
48 }
49}
50
51

Callers

nothing calls this directly

Calls 1

isEmptyMethod · 0.45

Tested by

no test coverage detected