Given a binary tree and a non negative integer k. Find and return the Kth maximum level sum in a binary tree. If the levels are less than k, return -1.
Output: 13. Explanation: The sums of nodes at each level are: Level 1: 1 Level 2: 2 + 3 = 5 Level 3: 4 + 5 + 6 + 7 = 22 Level 4: 8 + 9 = 17 Level 5: 10 + 11 = 21 The 2nd largest level sum is 21.
Input: root = [7, 9, 10, 12, 13, 14, 16, 25, 30], k = 2 Output: 13. Explanation: The sums of nodes at each level are: Level 1: 7. Level 2: 9 + 10 = 19. Level 3: 12 + 13 + 14 + 16 = 55. Level 4: 30+ 40 = 70. The 2nd largest level sum is 55.
Approach:
This can be solved using queue data structure afterwards keep finding the sum of each level and store the sum of each level in a vector say ans. Sort the ans array and print the kth maximum sum.
Below is the steps for above approach:
Create an empty queue q and push root in q.
Initialize vector ans.
Run while loop until q is not empty.
Initialize s=q.size()
Define a data structure vector V of size s
Run while loop until s-- .
Initialize temp = q.front() and store temp->data in V.
pop front node from q.
Push temp children i.e. temp->left then temp->right to q.
Initialize sum=0.
Add the element of V and store them in vector ans.
Sort the input array in the increasing order.
Return -1 if K-1 is equal or greater than ans.size() else return element at k-1 index.
// Java Code implementation for the avove approach:importjava.io.*;importjava.util.*;// Node classclassNode{intdata;Nodeleft,right;Node(intdata){this.data=data;left=null;right=null;}}classGFG{// Function to find the kThLargestLevelSumstaticintkthLargestLevelSum(Noderoot,intk){intans=Integer.MIN_VALUE;Queue<Node>q=newLinkedList<>();q.add(root);List<Integer>va=newArrayList<>();while(!q.isEmpty()){intsize=q.size();List<Integer>v=newArrayList<>(size);while(size-->0){Nodetemp=q.remove();v.add(temp.data);if(temp.left!=null){q.add(temp.left);}if(temp.right!=null){q.add(temp.right);}}intsum=0;for(inti:v){sum+=i;}va.add(sum);}Collections.sort(va,Collections.reverseOrder());if(va.size()<=k-1){return-1;}returnva.get(k-1);}publicstaticvoidmain(String[]args){Noderoot=newNode(7);root.left=newNode(9);root.right=newNode(10);root.left.left=newNode(12);root.left.right=newNode(13);root.left.left.left=newNode(30);root.left.left.right=newNode(40);root.right.left=newNode(14);root.right.right=newNode(16);intans=kthLargestLevelSum(root,2);System.out.println(ans);}}// This code is contributed by karthik.
Python3
# Python implementation of the above codeimportqueueclassNode:def__init__(self,data):self.data=dataself.left=Noneself.right=NonedefkthLargestLevelSum(root,k):ans=-float("inf")q=queue.Queue()q.put(root)va=[]whilenotq.empty():size=q.qsize()v=[]foriinrange(size):temp=q.get()v.append(temp.data)iftemp.left:q.put(temp.left)iftemp.right:q.put(temp.right)va.append(sum(v))va.sort(reverse=True)iflen(va)<=k-1:return-1returnva[k-1]if__name__=="__main__":root=Node(7)root.left=Node(9)root.right=Node(10)root.left.left=Node(12)root.left.right=Node(13)root.left.left.left=Node(30)root.left.left.right=Node(40)root.right.left=Node(14)root.right.right=Node(16)ans=kthLargestLevelSum(root,2)print(ans)# This code is contributed by prasad264
C#
// C# Code implementation for the avove approach:usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;// Node classclassNode{publicintdata;publicNodeleft,right;publicNode(intdata){this.data=data;left=null;right=null;}}publicclassGFG{// Function to find the kThLargestLevelSumstaticintkthLargestLevelSum(Noderoot,intk){intans=int.MinValue;Queue<Node>q=newQueue<Node>();q.Enqueue(root);List<int>va=newList<int>();while(q.Count!=0){intsize=q.Count;List<int>v=newList<int>(size);while(size-->0){Nodetemp=q.Dequeue();v.Add(temp.data);if(temp.left!=null){q.Enqueue(temp.left);}if(temp.right!=null){q.Enqueue(temp.right);}}intsum=0;foreach(intiinv){sum+=i;}va.Add(sum);}va.Sort();va.Reverse();if(va.Count<=k-1){return-1;}returnva[k-1];}staticpublicvoidMain(){// CodeNoderoot=newNode(7);root.left=newNode(9);root.right=newNode(10);root.left.left=newNode(12);root.left.right=newNode(13);root.left.left.left=newNode(30);root.left.left.right=newNode(40);root.right.left=newNode(14);root.right.right=newNode(16);intans=kthLargestLevelSum(root,2);Console.WriteLine(ans);}}// This code is contributed by sankar.
JavaScript
// JavaScript Code implementation for the avove approach:// Node classclassNode{constructor(data){this.data=data;this.left=null;this.right=null;}}// Function to find the kth largest level sumfunctionkthLargestLevelSum(root,k){varans=Number.MIN_VALUE;varq=[];q.push(root);letva=[];while(q.length>0){varsize=q.length;varv=[];while(size-->0){vartemp=q.shift();v.push(temp.data);if(temp.left!=null){q.push(temp.left);}if(temp.right!=null){q.push(temp.right);}}varsum=v.reduce((acc,curr)=>acc+curr,0);va.push(sum);}va.sort((a,b)=>b-a);if(va.length<=k-1){return-1;}returnva[k-1];}varroot=newNode(7);root.left=newNode(9);root.right=newNode(10);root.left.left=newNode(12);root.left.right=newNode(13);root.left.left.left=newNode(30);root.left.left.right=newNode(40);root.right.left=newNode(14);root.right.right=newNode(16);varans=kthLargestLevelSum(root,2);console.log(ans);// This code is contributed by lokesh.
Output
55
TimeComplexity: O(N log N), where N is the number of node in a binary tree. AuxiliarySpace: O(L), where L is the number of levels in a Binary tree.