Open In App

Sum of k smallest elements in BST

Last Updated : 14 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given Binary Search Tree. The task is to find sum of all elements smaller than and equal to Kth smallest element.

Examples: 

Input :  K = 3
              8
            /   \
           7     10
         /      /   \
        2      9     13
Output : 17
Explanation : Kth smallest element is 8 so sum of all
              element smaller than or equal to 8 are
              2 + 7 + 8

Input : K = 5
           8
         /   \
        5    11
      /  \
     2    7
      \
       3
Output :  25

Method 1 (Does not changes BST node structure): The idea is to traverse BST in inorder traversal. Note that Inorder traversal of BST accesses elements in sorted (or increasing) order. While traversing, we keep track of count of visited Nodes and keep adding Nodes until the count becomes k. 

Implementation:

C++




// c++ program to find Sum Of All Elements smaller
// than or equal to Kth Smallest Element In BST
#include <bits/stdc++.h>
using namespace std;
 
/* Binary tree Node */
struct Node
{
    int data;
    Node* left, * right;
};
 
// utility function new Node of BST
struct Node *createNode(int data)
{
    Node * new_Node = new Node;
    new_Node->left = NULL;
    new_Node->right = NULL;
    new_Node->data = data;
    return new_Node;
}
 
// A utility function to insert a new Node
//  with given key in BST and also maintain lcount ,Sum
struct Node * insert(Node *root, int key)
{
    // If the tree is empty, return a new Node
    if (root == NULL)
        return createNode(key);
 
    // Otherwise, recur down the tree
    if (root->data > key)
        root->left = insert(root->left, key);
 
    else if (root->data < key)
        root->right = insert(root->right, key);
 
    // return the (unchanged) Node pointer
    return root;
}
 
// function return sum of all element smaller than
// and equal to Kth smallest element
int ksmallestElementSumRec(Node *root, int k, int &count)
{
    // Base cases
    if (root == NULL)
        return 0;
    if (count > k)
        return 0;
 
    // Compute sum of elements in left subtree
    int res = ksmallestElementSumRec(root->left, k, count);
    if (count >= k)
        return res;
 
    // Add root's data
    res += root->data;
 
    // Add current Node
    count++;
    if (count >= k)
      return res;
 
    // If count is less than k, return right subtree Nodes
    return res + ksmallestElementSumRec(root->right, k, count);
}
 
// Wrapper over ksmallestElementSumRec()
int ksmallestElementSum(struct Node *root, int k)
{
   int count = 0;
   return ksmallestElementSumRec(root, k, count);
}
 
/* Driver program to test above functions */
int main()
{
 
    /*    20
        /    \
       8     22
     /   \
    4     12
         /   \
        10    14
          */
    Node *root = NULL;
    root = insert(root, 20);
    root = insert(root, 8);
    root = insert(root, 4);
    root = insert(root, 12);
    root = insert(root, 10);
    root = insert(root, 14);
    root = insert(root, 22);
 
    int k = 3;
    cout <<  ksmallestElementSum(root, k) <<endl;
    return 0;
}


Java




// Java program to find Sum Of All Elements smaller
// than or equal to Kth Smallest Element In BST
import java.util.*;
class GFG
{
 
  /* Binary tree Node */
  static class Node
  {
    int data;
    Node left,  right;
  };
 
  // utility function new Node of BST
  static Node createNode(int data)
  {
    Node  new_Node = new Node();
    new_Node.left = null;
    new_Node.right = null;
    new_Node.data = data;
    return new_Node;
  }
 
  // A utility function to insert a new Node
  //  with given key in BST and also maintain lcount ,Sum
  static Node  insert(Node root, int key)
  {
 
    // If the tree is empty, return a new Node
    if (root == null)
      return createNode(key);
 
    // Otherwise, recur down the tree
    if (root.data > key)
      root.left = insert(root.left, key);
    else if (root.data < key)
      root.right = insert(root.right, key);
 
    // return the (unchanged) Node pointer
    return root;
  }
 
 
  static int count = 0;
 
  // function return sum of all element smaller than
  // and equal to Kth smallest element
  static int ksmallestElementSumRec(Node root, int k)
  {
 
    // Base cases
    if (root == null)
      return 0;
    if (count > k)
      return 0;
 
    // Compute sum of elements in left subtree
    int res = ksmallestElementSumRec(root.left, k);
    if (count >= k)
      return res;
 
    // Add root's data
    res += root.data;
 
    // Add current Node
    count++;
    if (count >= k)
      return res;
 
    // If count is less than k, return right subtree Nodes
    return res + ksmallestElementSumRec(root.right, k);
  }
 
  // Wrapper over ksmallestElementSumRec()
  static int ksmallestElementSum(Node root, int k)
  {
 
    int res = ksmallestElementSumRec(root, k);
    return res;
  }
 
  /* Driver program to test above functions */
  public static void main(String[] args)
  {
 
    /*    20
        /    \
       8     22
     /   \
    4     12
         /   \
        10    14
          */
    Node root = null;
    root = insert(root, 20);
    root = insert(root, 8);
    root = insert(root, 4);
    root = insert(root, 12);
    root = insert(root, 10);
    root = insert(root, 14);
    root = insert(root, 22);
 
    int k = 3;
    int count = ksmallestElementSum(root, k);
    System.out.println(count);
  }
}
 
// This code is contributed by aashish1995


Python3




# Python3 program to find Sum Of All
# Elements smaller than or equal to
# Kth Smallest Element In BST
 
INT_MAX = 2147483647
 
# Binary Tree Node
""" utility that allocates a newNode
with the given key """
class createNode:
 
    # Construct to create a newNode
    def __init__(self, key):
        self.data = key
        self.left = None
        self.right = None
 
# A utility function to insert a new
# Node with given key in BST and also
# maintain lcount ,Sum
def insert(root, key) :
 
    # If the tree is empty, return a new Node
    if (root == None) :
        return createNode(key)
 
    # Otherwise, recur down the tree
    if (root.data > key) :
        root.left = insert(root.left, key)
 
    else if (root.data < key):
        root.right = insert(root.right, key)
 
    # return the (unchanged) Node pointer
    return root
 
# function return sum of all element smaller
# than and equal to Kth smallest element
def ksmallestElementSumRec(root, k, count) :
 
    # Base cases
    if (root == None) :
        return 0
    if (count[0] > k[0]) :
        return 0
 
    # Compute sum of elements in left subtree
    res = ksmallestElementSumRec(root.left, k, count)
    if (count[0] >= k[0]) :
        return res
 
    # Add root's data
    res += root.data
 
    # Add current Node
    count[0] += 1
    if (count[0] >= k[0]) :
        return res
 
    # If count is less than k, return
    # right subtree Nodes
    return res + ksmallestElementSumRec(root.right,
                                        k, count)
 
# Wrapper over ksmallestElementSumRec()
def ksmallestElementSum(root, k):
    count = [0]
    return ksmallestElementSumRec(root, k, count)
 
# Driver Code
if __name__ == '__main__':
 
    """ 20
        / \
    8 22
    / \
    4 12
        / \
        10 14
        """
    root = None
    root = insert(root, 20)
    root = insert(root, 8)
    root = insert(root, 4)
    root = insert(root, 12)
    root = insert(root, 10)
    root = insert(root, 14)
    root = insert(root, 22)
     
    k = [3]
    print(ksmallestElementSum(root, k))
 
# This code is contributed by
# Shubham Singh(SHUBHAMSINGH10)


C#




// C# program to find Sum Of All Elements smaller
// than or equal to Kth Smallest Element In BST
using System;
 
public class GFG
{
 
  /* Binary tree Node */
  public class Node
  {
    public int data;
    public Node left,  right;
  };
 
  // utility function new Node of BST
  static Node createNode(int data)
  {
    Node  new_Node = new Node();
    new_Node.left = null;
    new_Node.right = null;
    new_Node.data = data;
    return new_Node;
  }
 
  // A utility function to insert a new Node
  //  with given key in BST and also maintain lcount ,Sum
  static Node  insert(Node root, int key)
  {
 
    // If the tree is empty, return a new Node
    if (root == null)
      return createNode(key);
 
    // Otherwise, recur down the tree
    if (root.data > key)
      root.left = insert(root.left, key);
    else if (root.data < key)
      root.right = insert(root.right, key);
 
    // return the (unchanged) Node pointer
    return root;
  }
  static int count = 0;
 
  // function return sum of all element smaller than
  // and equal to Kth smallest element
  static int ksmallestElementSumRec(Node root, int k)
  {
 
    // Base cases
    if (root == null)
      return 0;
    if (count > k)
      return 0;
 
    // Compute sum of elements in left subtree
    int res = ksmallestElementSumRec(root.left, k);
    if (count >= k)
      return res;
 
    // Add root's data
    res += root.data;
 
    // Add current Node
    count++;
    if (count >= k)
      return res;
 
    // If count is less than k, return right subtree Nodes
    return res + ksmallestElementSumRec(root.right, k);
  }
 
  // Wrapper over ksmallestElementSumRec()
  static int ksmallestElementSum(Node root, int k)
  {
 
    int res = ksmallestElementSumRec(root, k);
    return res;
  }
 
  /* Driver program to test above functions */
  public static void Main(String[] args)
  {
 
    /*    20
        /    \
       8     22
     /   \
    4     12
         /   \
        10    14
          */
    Node root = null;
    root = insert(root, 20);
    root = insert(root, 8);
    root = insert(root, 4);
    root = insert(root, 12);
    root = insert(root, 10);
    root = insert(root, 14);
    root = insert(root, 22);
    int k = 3;
    int count = ksmallestElementSum(root, k);
    Console.WriteLine(count);
  }
}
 
// This code is contributed by aashish1995


Javascript




<script>
 
// JavaScript program to find
// Sum Of All Elements smaller
// than or equal to Kth Smallest Element In BST
 /* Binary tree Node */
class Node {
    constructor() {
        this.data = 0;
        this.left = null;
        this.right = null;
    }
}
 
  // utility function new Node of BST
  function createNode(data)
  {
    var  new_Node = new Node();
    new_Node.left = null;
    new_Node.right = null;
    new_Node.data = data;
    return new_Node;
  }
 
  // A utility function to insert a new Node
  //  with given key in BST and also maintain lcount ,Sum
  function  insert(root , key)
  {
 
    // If the tree is empty, return a new Node
    if (root == null)
      return createNode(key);
 
    // Otherwise, recur down the tree
    if (root.data > key)
      root.left = insert(root.left, key);
    else if (root.data < key)
      root.right = insert(root.right, key);
 
    // return the (unchanged) Node pointer
    return root;
  }
  var count = 0;
 
  // function return sum of all element smaller than
  // and equal to Kth smallest element
  function ksmallestElementSumRec(root , k)
  {
 
    // Base cases
    if (root == null)
      return 0;
    if (count > k)
      return 0;
 
    // Compute sum of elements in left subtree
    var res = ksmallestElementSumRec(root.left, k);
    if (count >= k)
      return res;
 
    // Add root's data
    res += root.data;
 
    // Add current Node
    count++;
    if (count >= k)
      return res;
 
    // If count is less than k, return right subtree Nodes
    return res + ksmallestElementSumRec(root.right, k);
  }
 
  // Wrapper over ksmallestElementSumRec()
  function ksmallestElementSum(root , k)
  {
 
    var res = ksmallestElementSumRec(root, k);
    return res;
  }
 
  /* Driver program to test above functions */
   
  
 
    /*    20
        /    \
       8     22
     /   \
    4     12
         /   \
        10    14
          */
    var root = null;
    root = insert(root, 20);
    root = insert(root, 8);
    root = insert(root, 4);
    root = insert(root, 12);
    root = insert(root, 10);
    root = insert(root, 14);
    root = insert(root, 22);
 
    var k = 3;
    var count = ksmallestElementSum(root, k);
    document.write(count);
 
// This code is contributed by todaysgaurav
 
</script>


Output

22

Time complexity: O(k)
Auxiliary Space: O(h), where h is the height of the tree
  
Method 2 (Efficient and changes structure of BST):

We can find the required sum in O(h) time where h is height of BST. Idea is similar to Kth-th smallest element in BST . Here we use augmented tree data structure to solve this problem efficiently in O(h) time [ h is height of BST ] .

Algorithm : 

BST Node contain to extra fields : Lcount , Sum

For each Node of BST
lCount : store how many left child it has
Sum     : store sum of all left child it has

Find Kth smallest element
[ temp_sum store sum of all element less than equal to K ]

ksmallestElementSumRec(root, K, temp_sum)

  IF root -> lCount == K + 1
      temp_sum += root->data + root->sum;
      break;
  ELSE
     IF k > root->lCount   // Goto right sub-tree
        temp_sum += root->data + root-> sum;
        ksmallestElementSumRec(root->right, K-root->lcount+1, temp_sum)
     ELSE
        // Goto left sub-tree
        ksmallestElementSumRec( root->left, K, temp_sum)

Below is implementation of above algo : 

C++




// C++ program to find Sum Of All Elements smaller
// than or equal to Kth Smallest Element In BST
#include <bits/stdc++.h>
using namespace std;
 
/* Binary tree Node */
struct Node
{
    int data;
    int lCount;
    int Sum ;
    Node* left;
    Node* right;
};
 
//utility function new Node of BST
struct Node *createNode(int data)
{
    Node * new_Node = new Node;
    new_Node->left = NULL;
    new_Node->right = NULL;
    new_Node->data = data;
    new_Node->lCount = 0 ;
    new_Node->Sum = 0;
    return new_Node;
}
 
// A utility function to insert a new Node with
// given key in BST and also maintain lcount ,Sum
struct Node * insert(Node *root, int key)
{
    // If the tree is empty, return a new Node
    if (root == NULL)
        return createNode(key);
 
    // Otherwise, recur down the tree
    if (root->data > key)
    {
        // increment lCount of current Node
        root->lCount++;
 
        // increment current Node sum by adding
        // key into it
        root->Sum += key;
 
        root->left= insert(root->left , key);
    }
    else if (root->data < key )
        root->right= insert (root->right , key );
 
    // return the (unchanged) Node pointer
    return root;
}
 
// function return sum of all element smaller than and equal
// to Kth smallest element
void ksmallestElementSumRec(Node *root, int k , int &temp_sum)
{
    if (root == NULL)
        return ;
 
    // if we fount k smallest element then break the function
    if ((root->lCount + 1) == k)
    {
        temp_sum += root->data + root->Sum ;
        return ;
    }
 
    else if (k > root->lCount)
    {
        // store sum of all element smaller than current root ;
        temp_sum += root->data + root->Sum;
 
        // decremented k and call right sub-tree
        k = k -( root->lCount + 1);
        ksmallestElementSumRec(root->right , k , temp_sum);
    }
    else // call left sub-tree
        ksmallestElementSumRec(root->left , k , temp_sum );
}
 
// Wrapper over ksmallestElementSumRec()
int ksmallestElementSum(struct Node *root, int k)
{
    int sum = 0;
    ksmallestElementSumRec(root, k, sum);
    return sum;
}
 
/* Driver program to test above functions */
int main()
{
    /*    20
        /    \
       8     22
     /   \
    4     12
         /   \
        10    14
          */
    Node *root = NULL;
    root = insert(root, 20);
    root = insert(root, 8);
    root = insert(root, 4);
    root = insert(root, 12);
    root = insert(root, 10);
    root = insert(root, 14);
    root = insert(root, 22);
 
    int k = 3;
    cout <<  ksmallestElementSum(root, k) << endl;
    return 0;
}


Java




// Java program to find Sum Of All Elements smaller
// than or equal to Kth Smallest Element In BST
 
import java.util.*;
 
class GFG{
 
/* Binary tree Node */
static class Node
{
    int data;
    int lCount;
    int Sum ;
    Node left;
    Node right;
};
 
//utility function new Node of BST
static Node createNode(int data)
{
    Node  new_Node = new Node();
    new_Node.left = null;
    new_Node.right = null;
    new_Node.data = data;
    new_Node.lCount = 0 ;
    new_Node.Sum = 0;
    return new_Node;
}
 
// A utility function to insert a new Node with
// given key in BST and also maintain lcount ,Sum
static Node  insert(Node root, int key)
{
    // If the tree is empty, return a new Node
    if (root == null)
        return createNode(key);
 
    // Otherwise, recur down the tree
    if (root.data > key)
    {
        // increment lCount of current Node
        root.lCount++;
 
        // increment current Node sum by adding
        // key into it
        root.Sum += key;
 
        root.left= insert(root.left , key);
    }
    else if (root.data < key )
        root.right= insert (root.right , key );
 
    // return the (unchanged) Node pointer
    return root;
}
 
static int temp_sum;
// function return sum of all element smaller than and equal
// to Kth smallest element
static void ksmallestElementSumRec(Node root, int k )
{
    if (root == null)
        return ;
 
    // if we fount k smallest element then break the function
    if ((root.lCount + 1) == k)
    {
        temp_sum += root.data + root.Sum ;
        return ;
    }
 
    else if (k > root.lCount)
    {
        // store sum of all element smaller than current root ;
        temp_sum += root.data + root.Sum;
 
        // decremented k and call right sub-tree
        k = k -( root.lCount + 1);
        ksmallestElementSumRec(root.right , k );
    }
    else // call left sub-tree
        ksmallestElementSumRec(root.left , k );
}
 
// Wrapper over ksmallestElementSumRec()
static void ksmallestElementSum(Node root, int k)
{
    temp_sum = 0;
    ksmallestElementSumRec(root, k);
}
 
/* Driver program to test above functions */
public static void main(String[] args)
{
    /*    20
        /    \
       8     22
     /   \
    4     12
         /   \
        10    14
          */
    Node root = null;
    root = insert(root, 20);
    root = insert(root, 8);
    root = insert(root, 4);
    root = insert(root, 12);
    root = insert(root, 10);
    root = insert(root, 14);
    root = insert(root, 22);
 
    int k = 3;
     ksmallestElementSum(root, k);
     System.out.println(temp_sum);
}
}
 
// This code is contributed by gauravrajput1


Python3




# Python3 program to find Sum Of All Elements
# smaller than or equal to Kth Smallest Element In BST
 
# utility function new Node of BST
class createNode:
 
    # Constructor to create a new node
    def __init__(self, data):
        self.data = data
        self.lCount = 0
        self.Sum = 0
        self.left = None
        self.right = None
 
# A utility function to insert a new Node with
# given key in BST and also maintain lcount ,Sum
def insert(root, key):
     
    # If the tree is empty, return a new Node
    if root == None:
        return createNode(key)
 
    # Otherwise, recur down the tree
    if root.data > key:
         
        # increment lCount of current Node
        root.lCount += 1
 
        # increment current Node sum by
        # adding key into it
        root.Sum += key
 
        root.left= insert(root.left , key)
    else if root.data < key:
        root.right= insert (root.right , key)
 
    # return the (unchanged) Node pointer
    return root
 
# function return sum of all element smaller
# than and equal to Kth smallest element
def ksmallestElementSumRec(root, k , temp_sum):
    if root == None:
        return
 
    # if we fount k smallest element
    # then break the function
    if (root.lCount + 1) == k:
        temp_sum[0] += root.data + root.Sum
        return
 
    else if k > root.lCount:
         
        # store sum of all element smaller
        # than current root ;
        temp_sum[0] += root.data + root.Sum
 
        # decremented k and call right sub-tree
        k = k -( root.lCount + 1)
        ksmallestElementSumRec(root.right,
                               k, temp_sum)
    else: # call left sub-tree
        ksmallestElementSumRec(root.left,
                               k, temp_sum)
 
# Wrapper over ksmallestElementSumRec()
def ksmallestElementSum(root, k):
    Sum = [0]
    ksmallestElementSumRec(root, k, Sum)
    return Sum[0]
 
# Driver Code
if __name__ == '__main__':
     
    # 20
    # / \
    # 8     22
    # / \
    #4     12
    #     / \
    # 10 14
    #    
    root = None
    root = insert(root, 20)
    root = insert(root, 8)
    root = insert(root, 4)
    root = insert(root, 12)
    root = insert(root, 10)
    root = insert(root, 14)
    root = insert(root, 22)
 
    k = 3
    print(ksmallestElementSum(root, k))
 
# This code is contributed by PranchalK


C#




// C# program to find Sum Of All Elements smaller
// than or equal tp Kth Smallest Element In BST
using System;
public class GFG
{
 
/* Binary tree Node */
public class Node
{
   public int data;
   public int lCount;
   public int Sum ;
   public Node left;
   public Node right;
};
 
// utility function new Node of BST
static Node createNode(int data)
{
    Node  new_Node = new Node();
    new_Node.left = null;
    new_Node.right = null;
    new_Node.data = data;
    new_Node.lCount = 0 ;
    new_Node.Sum = 0;
    return new_Node;
}
 
// A utility function to insert a new Node with
// given key in BST and also maintain lcount ,Sum
static Node  insert(Node root, int key)
{
   
    // If the tree is empty, return a new Node
    if (root == null)
        return createNode(key);
 
    // Otherwise, recur down the tree
    if (root.data > key)
    {
       
        // increment lCount of current Node
        root.lCount++;
 
        // increment current Node sum by adding
        // key into it
        root.Sum += key;
        root.left = insert(root.left , key);
    }
    else if (root.data < key )
        root.right = insert (root.right , key );
 
    // return the (unchanged) Node pointer
    return root;
}
 
static int temp_sum;
   
// function return sum of all element smaller than and equal
// to Kth smallest element
static void ksmallestElementSumRec(Node root, int k )
{
    if (root == null)
        return ;
 
    // if we fount k smallest element then break the function
    if ((root.lCount + 1) == k)
    {
        temp_sum += root.data + root.Sum ;
        return ;
    }
 
    else if (k > root.lCount)
    {
       
        // store sum of all element smaller than current root ;
        temp_sum += root.data + root.Sum;
 
        // decremented k and call right sub-tree
        k = k -( root.lCount + 1);
        ksmallestElementSumRec(root.right , k );
    }
    else // call left sub-tree
        ksmallestElementSumRec(root.left , k );
}
 
// Wrapper over ksmallestElementSumRec()
static void ksmallestElementSum(Node root, int k)
{
    temp_sum = 0;
    ksmallestElementSumRec(root, k);
}
 
/* Driver program to test above functions */
public static void Main(String[] args)
{
    /*    20
        /    \
       8     22
     /   \
    4     12
         /   \
        10    14
          */
    Node root = null;
    root = insert(root, 20);
    root = insert(root, 8);
    root = insert(root, 4);
    root = insert(root, 12);
    root = insert(root, 10);
    root = insert(root, 14);
    root = insert(root, 22);
 
    int k = 3;
     ksmallestElementSum(root, k);
     Console.WriteLine(temp_sum);
}
}
 
// This code is contributed by gauravrajput1


Javascript




<script>
 
      // JavaScript program to find Sum Of All Elements smaller
      // than or equal to Kth Smallest Element In BST
      /* Binary tree Node */
      class Node {
        constructor() {
          this.data = 0;
          this.lCount = 0;
          this.Sum = 0;
          this.left = null;
          this.right = null;
        }
      }
 
      // utility function new Node of BST
      function createNode(data) {
        var new_Node = new Node();
        new_Node.left = null;
        new_Node.right = null;
        new_Node.data = data;
        new_Node.lCount = 0;
        new_Node.Sum = 0;
        return new_Node;
      }
 
      // A utility function to insert a new Node with
      // given key in BST and also maintain lcount ,Sum
      function insert(root, key) {
        // If the tree is empty, return a new Node
        if (root == null) return createNode(key);
 
        // Otherwise, recur down the tree
        if (root.data > key) {
          // increment lCount of current Node
          root.lCount++;
 
          // increment current Node sum by adding
          // key into it
          root.Sum += key;
          root.left = insert(root.left, key);
        } else if (root.data < key)
        root.right = insert(root.right, key);
 
        // return the (unchanged) Node pointer
        return root;
      }
 
      var temp_sum = 0;
 
      // function return sum of all element smaller than and equal
      // to Kth smallest element
      function ksmallestElementSumRec(root, k) {
        if (root == null) return;
 
        // if we fount k smallest element then break the function
        if (root.lCount + 1 == k) {
          temp_sum += root.data + root.Sum;
          return;
        } else if (k > root.lCount) {
          // store sum of all element smaller than current root ;
          temp_sum += root.data + root.Sum;
 
          // decremented k and call right sub-tree
          k = k - (root.lCount + 1);
          ksmallestElementSumRec(root.right, k);
        } // call left sub-tree
        else ksmallestElementSumRec(root.left, k);
      }
 
      // Wrapper over ksmallestElementSumRec()
      function ksmallestElementSum(root, k) {
        temp_sum = 0;
        ksmallestElementSumRec(root, k);
      }
 
      /* Driver program to test above functions */
      /*  20
        /    \
       8     22
     /   \
    4     12
         /   \
        10    14
          */
      var root = null;
      root = insert(root, 20);
      root = insert(root, 8);
      root = insert(root, 4);
      root = insert(root, 12);
      root = insert(root, 10);
      root = insert(root, 14);
      root = insert(root, 22);
 
      var k = 3;
      ksmallestElementSum(root, k);
      document.write(temp_sum);
       
</script>


Output

22

Time Complexity: O(h) where h is height of tree. 

Auxiliary Space: O(1)

Playlist : Trees | Data Structures & Algorithms | Programming Tutorials | GeeksforGeeks

 



Previous Article
Next Article

Similar Reads

Find k-th smallest element in BST (Order Statistics in BST)
Given the root of a binary search tree and K as input, find Kth smallest element in BST. For example, in the following BST, if k = 3, then the output should be 10, and if k = 5, then the output should be 14. Recommended: Please solve it on "PRACTICE" first, before moving on to the solution.Method 1: Using Inorder Traversal (O(n) time and O(h) auxil
31 min read
Two nodes of a BST are swapped, correct the BST
Two of the nodes of a Binary Search Tree (BST) are swapped. Fix (or correct) the BST. Input: x = 20, y = 8 10 / \ 5 8 / \ 2 20Output: 10 / \ 5 20 / \ 2 8 Input: x = 10 y = 5 10 / \ 5 8 / \ 2 20Output: 5 / \ 10 20 / \ 2 8 Recommended ProblemFixing Two swapped nodes of a BSTSolve Problem Approach: The in-order traversal of a BST produces a sorted arr
23 min read
POTD Solutions | 15 Oct' 23 | Normal BST to Balanced BST
View all POTD Solutions Welcome to the daily solutions of our PROBLEM OF THE DAY (POTD). We will discuss the entire problem step-by-step and work towards developing an optimized solution. This will not only help you brush up on your concepts of Binary Search Trees but will also help you build up problem-solving skills. [caption width="800"]Geeksfor
5 min read
K'th Largest Element in BST when modification to BST is not allowed
Given a Binary Search Tree (BST) and a positive integer k, find the k'th largest element in the Binary Search Tree. For example, in the following BST, if k = 3, then output should be 14, and if k = 5, then output should be 10. We have discussed two methods in this post. The method 1 requires O(n) time. The method 2 takes O(h) time where h is height
22 min read
Smallest number in BST which is greater than or equal to N
Given a Binary Search Tree and a number N, the task is to find the smallest number in the binary search tree that is greater than or equal to N. Print the value of the element if it exists otherwise print -1. Examples: Input: N = 20 Output: 21 Explanation: 21 is the smallest element greater than 20. Input: N = 18 Output: 19 Explanation: 19 is the s
9 min read
Smallest number in BST which is greater than or equal to N ( Iterative Approach)
Given a Binary Search Tree and a number N, the task is to find the smallest number in the binary search tree that is greater than or equal to N. Examples: Input: N = 5 8 / \ 7 10 / / \ 2 9 13 Output: 7 As 7 is the smallest number in BST which is greater than N = 5. Input: N = 10 8 / \ 5 11 / \ 2 7 \ 3 Output: 11 As 11 is the smallest number in BST
8 min read
Find Median in BST Subtree from Kth Smallest Node
Given a binary search tree, the task is to find the median of the subtree rooted with Kth smallest node of the tree. Examples: Input: N = 12, K = 9 50 / \ 25 75 / \ \ 15 45 90 / \ / \ / \11 20 30 49 80 100 Output: 85Explanation: K=9. So the 9th smallest number is 75. The values of this subtree are 75 80 90 100. Now, the median of this is (80+90)/2
7 min read
K'th smallest element in BST using O(1) Extra Space
Given a Binary Search Tree (BST) and a positive integer k, find the k'th smallest element in the Binary Search Tree. For example, in the following BST, if k = 3, then output should be 10, and if k = 5, then output should be 14. We have discussed two methods in this post and one method in this post. All of the previous methods require extra space. H
13 min read
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 el
9 min read
Sum of K largest elements in BST using O(1) Extra space
Given a BST, the task is to find the sum of all elements greater than or equal to K-th largest element in O(1) space.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: 2
9 min read