Kth Maximum Level sum
Last Updated :
18 Apr, 2023
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.
Examples:
Input: root = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], k = 2
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.
C++
#include <bits/stdc++.h>
using namespace std;
class Node {
public :
int data;
Node *left, *right;
Node( int data)
{
this ->data = data;
left = NULL;
right = NULL;
}
};
long long kthLargestLevelSum(Node* root, int k)
{
long long ans = INT_MIN;
queue<Node*> q;
q.push(root);
vector< long long int > va;
while (!q.empty()) {
int size = q.size();
vector< long long > v(size);
while (size--) {
Node* temp = q.front();
q.pop();
v.push_back(temp->data);
if (temp->left) {
q.push(temp->left);
}
if (temp->right) {
q.push(temp->right);
}
}
long long sum = 0;
for ( auto i : v) {
sum += i;
}
va.push_back(sum);
}
sort(va.begin(), va.end(), greater< long long >());
if (va.size() <= k - 1) {
return -1;
}
return va[k - 1];
}
int main()
{
Node* root = new Node(7);
root->left = new Node(9);
root->right = new Node(10);
root->left->left = new Node(12);
root->left->right = new Node(13);
root->left->left->left = new Node(30);
root->left->left->right = new Node(40);
root->right->left = new Node(14);
root->right->right = new Node(16);
long long ans = kthLargestLevelSum(root, 2);
cout << ans << endl;
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class Node {
int data;
Node left, right;
Node( int data)
{
this .data = data;
left = null ;
right = null ;
}
}
class GFG {
static int kthLargestLevelSum(Node root, int k)
{
int ans = Integer.MIN_VALUE;
Queue<Node> q = new LinkedList<>();
q.add(root);
List<Integer> va = new ArrayList<>();
while (!q.isEmpty()) {
int size = q.size();
List<Integer> v = new ArrayList<>(size);
while (size-- > 0 ) {
Node temp = q.remove();
v.add(temp.data);
if (temp.left != null ) {
q.add(temp.left);
}
if (temp.right != null ) {
q.add(temp.right);
}
}
int sum = 0 ;
for ( int i : v) {
sum += i;
}
va.add(sum);
}
Collections.sort(va, Collections.reverseOrder());
if (va.size() <= k - 1 ) {
return - 1 ;
}
return va.get(k - 1 );
}
public static void main(String[] args)
{
Node root = new Node( 7 );
root.left = new Node( 9 );
root.right = new Node( 10 );
root.left.left = new Node( 12 );
root.left.right = new Node( 13 );
root.left.left.left = new Node( 30 );
root.left.left.right = new Node( 40 );
root.right.left = new Node( 14 );
root.right.right = new Node( 16 );
int ans = kthLargestLevelSum(root, 2 );
System.out.println(ans);
}
}
|
Python3
import queue
class Node:
def __init__( self , data):
self .data = data
self .left = None
self .right = None
def kthLargestLevelSum(root, k):
ans = - float ( "inf" )
q = queue.Queue()
q.put(root)
va = []
while not q.empty():
size = q.qsize()
v = []
for i in range (size):
temp = q.get()
v.append(temp.data)
if temp.left:
q.put(temp.left)
if temp.right:
q.put(temp.right)
va.append( sum (v))
va.sort(reverse = True )
if len (va) < = k - 1 :
return - 1
return va[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)
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
class Node {
public int data;
public Node left, right;
public Node( int data)
{
this .data = data;
left = null ;
right = null ;
}
}
public class GFG {
static int kthLargestLevelSum(Node root, int k)
{
int ans = int .MinValue;
Queue<Node> q = new Queue<Node>();
q.Enqueue(root);
List< int > va = new List< int >();
while (q.Count != 0) {
int size = q.Count;
List< int > v = new List< int >(size);
while (size-- > 0) {
Node temp = q.Dequeue();
v.Add(temp.data);
if (temp.left != null ) {
q.Enqueue(temp.left);
}
if (temp.right != null ) {
q.Enqueue(temp.right);
}
}
int sum = 0;
foreach ( int i in v) { sum += i; }
va.Add(sum);
}
va.Sort();
va.Reverse();
if (va.Count <= k - 1) {
return -1;
}
return va[k - 1];
}
static public void Main()
{
Node root = new Node(7);
root.left = new Node(9);
root.right = new Node(10);
root.left.left = new Node(12);
root.left.right = new Node(13);
root.left.left.left = new Node(30);
root.left.left.right = new Node(40);
root.right.left = new Node(14);
root.right.right = new Node(16);
int ans = kthLargestLevelSum(root, 2);
Console.WriteLine(ans);
}
}
|
Javascript
class Node {
constructor(data) {
this .data = data;
this .left = null ;
this .right = null ;
}
}
function kthLargestLevelSum(root, k) {
var ans = Number.MIN_VALUE;
var q = [];
q.push(root);
let va = [];
while (q.length > 0) {
var size = q.length;
var v = [];
while (size-- > 0) {
var temp = q.shift();
v.push(temp.data);
if (temp.left != null ) {
q.push(temp.left);
}
if (temp.right != null ) {
q.push(temp.right);
}
}
var sum = v.reduce((acc, curr) => acc + curr, 0);
va.push(sum);
}
va.sort((a, b) => b - a);
if (va.length <= k - 1) {
return -1;
}
return va[k - 1];
}
var root = new Node(7);
root.left = new Node(9);
root.right = new Node(10);
root.left.left = new Node(12);
root.left.right = new Node(13);
root.left.left.left = new Node(30);
root.left.left.right = new Node(40);
root.right.left = new Node(14);
root.right.right = new Node(16);
var ans = kthLargestLevelSum(root, 2);
console.log(ans);
|
Time Complexity: O(N log N), where N is the number of node in a binary tree.
Auxiliary Space: O(L), where L is the number of levels in a Binary tree.
Share your thoughts in the comments
Please Login to comment...