Sum of k largest elements in BST

Given a BST, the task is to find the sum of all elements greater than and equal to kth largest element.

Examples:  

Input : K = 3
              8
            /   \
           7     10
         /      /   \
        2      9     13
Output : 32
Explanation: 3rd largest element is 9 so sum of all
             elements greater than or equal to 9 are
             9 + 10 + 13 = 32.

Input : K = 2
           8
         /   \
        5    11
      /  \
     2    7
      \
       3
Output : 19
Explanation: 2nd largest element is 8 so sum of all
             elements greater than or equal to 8 are
             8 + 11 = 19.



Approach: 
The idea is to traverse BST in Inorder traversal in a reverse way (Right Root Left). 
Note that Inorder traversal of BST accesses elements in a sorted (or increasing) order, hence the reverse of inorder traversal will be in a sorted order(decreasing). While traversing, keep track of the count of visited Nodes and keep adding Nodes until the count becomes k. 

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to find Sum Of All Elements larger
// than or equal to Kth Largest Element In BST
#include <bits/stdc++.h>
using namespace std;
 
struct Node {
    int data;
    Node *left, *right;
};
 
// utility function new Node of BST
struct Node* cNode(int data)
{
    Node* node = new Node;
    node->left = NULL;
    node->right = NULL;
    node->data = data;
    return node;
}
 
// A utility function to insert a new Node
// with given key in BST
struct Node* add(Node* root, int key)
{
    // If the tree is empty, return a new Node
    if (root == NULL)
        return cNode(key);
 
    // Otherwise, recur down the tree
    if (root->data > key)
        root->left = add(root->left, key);
 
    else if (root->data < key)
        root->right = add(root->right, key);
 
    // return the (unchanged) Node pointer
    return root;
}
 
// function to return sum of all elements larger than
// and equal to Kth largest element
int klargestElementSumUtil(Node* root, int k, int& c)
{
    // Base cases
    if (root == NULL)
        return 0;
    if (c > k)
        return 0;
 
    // Compute sum of elements in right subtree
    int ans = klargestElementSumUtil(root->right, k, c);
    if (c >= k)
        return ans;
 
    // Add root's data
    ans += root->data;
 
    // Add current Node
    c++;
    if (c >= k)
        return ans;
 
    // If c is less than k, return left subtree Nodes
    return ans + klargestElementSumUtil(root->left, k, c);
}
 
// Wrapper over klargestElementSumRec()
int klargestElementSum(struct Node* root, int k)
{
    int c = 0;
    klargestElementSumUtil(root, k, c);
}
 
// Drivers code
int main()
{
    /*   19
        /    \
       7     21
     /   \
    3     11
         /   \
        9    13
          */
 
    Node* root = NULL;
    root = add(root, 19);
    root = add(root, 7);
    root = add(root, 3);
    root = add(root, 11);
    root = add(root, 9);
    root = add(root, 13);
    root = add(root, 21);
 
    int k = 2;
    cout << klargestElementSum(root, k) << endl;
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to find Sum Of All Elements larger
// than or equal to Kth Largest Element In BST
import java.util.*;
 
class GFG
{
 
static class Node
{
    int data;
    Node left, right;
};
static int c;
 
// Utility function new Node of BST
static Node cNode(int data)
{
    Node node = new Node();
    node.left = null;
    node.right = null;
    node.data = data;
    return node;
}
 
// A utility function to insert a new Node
// with given key in BST
static Node add(Node root, int key)
{
    // If the tree is empty, return a new Node
    if (root == null)
        return cNode(key);
 
    // Otherwise, recur down the tree
    if (root.data > key)
        root.left = add(root.left, key);
 
    else if (root.data < key)
        root.right = add(root.right, key);
 
    // return the (unchanged) Node pointer
    return root;
}
 
// function to return sum of all elements larger than
// and equal to Kth largest element
static int klargestElementSumUtil(Node root, int k)
{
    // Base cases
    if (root == null)
        return 0;
    if (c > k)
        return 0;
 
    // Compute sum of elements in right subtree
    int ans = klargestElementSumUtil(root.right, k);
    if (c >= k)
        return ans;
 
    // Add root's data
    ans += root.data;
 
    // Add current Node
    c++;
    if (c >= k)
        return ans;
 
    // If c is less than k, return left subtree Nodes
    return ans + klargestElementSumUtil(root.left, k);
}
 
// Wrapper over klargestElementSumRec()
static int klargestElementSum(Node root, int k)
{
    c = 0;
    return klargestElementSumUtil(root, k);
}
 
// Drivers code
public static void main(String[] args)
{
    /* 19
        / \
    7     21
    / \
    3     11
        / \
        9 13
        */
 
    Node root = null;
    root = add(root, 19);
    root = add(root, 7);
    root = add(root, 3);
    root = add(root, 11);
    root = add(root, 9);
    root = add(root, 13);
    root = add(root, 21);
 
    int k = 2;
    System.out.print(klargestElementSum(root, k) +"\n");
}
}
 
// This code is contributed by PrinciRaj1992

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to find sum of all elements larger
# than or equal to Kth largest element In BST
c = 0
 
class cNode:
     
    def __init__(self, data):
         
        self.data = data
        self.left = None
        self.right = None
 
# A utility function to insert a new Node
# with given key in BST
def add(root, key):
     
    # If the tree is empty, return a new Node
    if (root == None):
        return cNode(key)
 
    # Otherwise, recur down the tree
    if (root.data > key):
        root.left = add(root.left, key)
 
    elif(root.data < key):
        root.right = add(root.right, key)
 
    # return the (unchanged) Node pointer
    return root
 
# Function to return sum of all elements
# larger than and equal to Kth largest element
def klargestElementSumUtil(root, k):
     
    global c
     
    # Base cases
    if (root == None):
        return 0
    if (c > k):
        return 0
 
    # Compute sum of elements in right subtree
    ans = klargestElementSumUtil(root.right, k)
     
    if (c >= k):
        return ans
 
    # Add root's data
    ans += root.data
 
    # Add current Node
    c += 1
     
    if (c >= k):
        return ans
 
    # If c is less than k, return left subtree Nodes
    return ans + klargestElementSumUtil(root.left, k)
 
# Wrapper over klargestElementSumRec()
def klargestElementSum(root, k):
     
    return klargestElementSumUtil(root, k)
 
# Driver code
if __name__ == '__main__':
     
    '''
    /*    19
        /    \
       7     21
     /   \
    3     11
         /   \
        9    13
          */ '''
    root = None
    root = add(root, 19)
    root = add(root, 7)
    root = add(root, 3)
    root = add(root, 11)
    root = add(root, 9)
    root = add(root, 13)
    root = add(root, 21)
 
    k = 2
     
    print(klargestElementSum(root, k))
     
# This code is contributed by bgangwar59

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to find Sum Of All Elements larger
// than or equal to Kth Largest Element In BST
using System;
 
class GFG
{
 
class Node
{
    public int data;
    public Node left, right;
};
static int c;
 
// Utility function new Node of BST
static Node cNode(int data)
{
    Node node = new Node();
    node.left = null;
    node.right = null;
    node.data = data;
    return node;
}
 
// A utility function to insert a new Node
// with given key in BST
static Node add(Node root, int key)
{
    // If the tree is empty, return a new Node
    if (root == null)
        return cNode(key);
 
    // Otherwise, recur down the tree
    if (root.data > key)
        root.left = add(root.left, key);
 
    else if (root.data < key)
        root.right = add(root.right, key);
 
    // return the (unchanged) Node pointer
    return root;
}
 
// function to return sum of all elements larger than
// and equal to Kth largest element
static int klargestElementSumUtil(Node root, int k)
{
    // Base cases
    if (root == null)
        return 0;
    if (c > k)
        return 0;
 
    // Compute sum of elements in right subtree
    int ans = klargestElementSumUtil(root.right, k);
    if (c >= k)
        return ans;
 
    // Add root's data
    ans += root.data;
 
    // Add current Node
    c++;
    if (c >= k)
        return ans;
 
    // If c is less than k, return left subtree Nodes
    return ans + klargestElementSumUtil(root.left, k);
}
 
// Wrapper over klargestElementSumRec()
static int klargestElementSum(Node root, int k)
{
    c = 0;
    return klargestElementSumUtil(root, k);
}
 
// Drivers code
public static void Main(String[] args)
{
    /* 19
        / \
    7     21
    / \
    3     11
        / \
        9 13
        */
 
    Node root = null;
    root = add(root, 19);
    root = add(root, 7);
    root = add(root, 3);
    root = add(root, 11);
    root = add(root, 9);
    root = add(root, 13);
    root = add(root, 21);
 
    int k = 2;
    Console.Write(klargestElementSum(root, k) +"\n");
}
}
 
// This code is contributed by PrinciRaj1992

chevron_right


Output: 

40


 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : princiraj1992, bgangwar59

Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.