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++
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int data;
Node* left, * right;
};
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;
}
struct Node * insert(Node *root, int key)
{
if (root == NULL)
return createNode(key);
if (root->data > key)
root->left = insert(root->left, key);
else if (root->data < key)
root->right = insert(root->right, key);
return root;
}
int ksmallestElementSumRec(Node *root, int k, int &count)
{
if (root == NULL)
return 0;
if (count > k)
return 0;
int res = ksmallestElementSumRec(root->left, k, count);
if (count >= k)
return res;
res += root->data;
count++;
if (count >= k)
return res;
return res + ksmallestElementSumRec(root->right, k, count);
}
int ksmallestElementSum( struct Node *root, int k)
{
int count = 0;
return ksmallestElementSumRec(root, k, count);
}
int main()
{
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
import java.util.*;
class GFG
{
static class Node
{
int data;
Node left, right;
};
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;
}
static Node insert(Node root, int key)
{
if (root == null )
return createNode(key);
if (root.data > key)
root.left = insert(root.left, key);
else if (root.data < key)
root.right = insert(root.right, key);
return root;
}
static int count = 0 ;
static int ksmallestElementSumRec(Node root, int k)
{
if (root == null )
return 0 ;
if (count > k)
return 0 ;
int res = ksmallestElementSumRec(root.left, k);
if (count >= k)
return res;
res += root.data;
count++;
if (count >= k)
return res;
return res + ksmallestElementSumRec(root.right, k);
}
static int ksmallestElementSum(Node root, int k)
{
int res = ksmallestElementSumRec(root, k);
return res;
}
public static void main(String[] args)
{
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);
}
}
|
Python3
INT_MAX = 2147483647
class createNode:
def __init__( self , key):
self .data = key
self .left = None
self .right = None
def insert(root, key) :
if (root = = None ) :
return createNode(key)
if (root.data > key) :
root.left = insert(root.left, key)
else if (root.data < key):
root.right = insert(root.right, key)
return root
def ksmallestElementSumRec(root, k, count) :
if (root = = None ) :
return 0
if (count[ 0 ] > k[ 0 ]) :
return 0
res = ksmallestElementSumRec(root.left, k, count)
if (count[ 0 ] > = k[ 0 ]) :
return res
res + = root.data
count[ 0 ] + = 1
if (count[ 0 ] > = k[ 0 ]) :
return res
return res + ksmallestElementSumRec(root.right,
k, count)
def ksmallestElementSum(root, k):
count = [ 0 ]
return ksmallestElementSumRec(root, k, count)
if __name__ = = '__main__' :
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))
|
C#
using System;
public class GFG
{
public class Node
{
public int data;
public Node left, right;
};
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;
}
static Node insert(Node root, int key)
{
if (root == null )
return createNode(key);
if (root.data > key)
root.left = insert(root.left, key);
else if (root.data < key)
root.right = insert(root.right, key);
return root;
}
static int count = 0;
static int ksmallestElementSumRec(Node root, int k)
{
if (root == null )
return 0;
if (count > k)
return 0;
int res = ksmallestElementSumRec(root.left, k);
if (count >= k)
return res;
res += root.data;
count++;
if (count >= k)
return res;
return res + ksmallestElementSumRec(root.right, k);
}
static int ksmallestElementSum(Node root, int k)
{
int res = ksmallestElementSumRec(root, k);
return res;
}
public static void Main(String[] args)
{
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);
}
}
|
Javascript
<script>
class Node {
constructor() {
this .data = 0;
this .left = null ;
this .right = null ;
}
}
function createNode(data)
{
var new_Node = new Node();
new_Node.left = null ;
new_Node.right = null ;
new_Node.data = data;
return new_Node;
}
function insert(root , key)
{
if (root == null )
return createNode(key);
if (root.data > key)
root.left = insert(root.left, key);
else if (root.data < key)
root.right = insert(root.right, key);
return root;
}
var count = 0;
function ksmallestElementSumRec(root , k)
{
if (root == null )
return 0;
if (count > k)
return 0;
var res = ksmallestElementSumRec(root.left, k);
if (count >= k)
return res;
res += root.data;
count++;
if (count >= k)
return res;
return res + ksmallestElementSumRec(root.right, k);
}
function ksmallestElementSum(root , k)
{
var res = ksmallestElementSumRec(root, k);
return res;
}
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);
</script>
|
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++
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int data;
int lCount;
int Sum ;
Node* left;
Node* right;
};
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;
}
struct Node * insert(Node *root, int key)
{
if (root == NULL)
return createNode(key);
if (root->data > key)
{
root->lCount++;
root->Sum += key;
root->left= insert(root->left , key);
}
else if (root->data < key )
root->right= insert (root->right , key );
return root;
}
void ksmallestElementSumRec(Node *root, int k , int &temp_sum)
{
if (root == NULL)
return ;
if ((root->lCount + 1) == k)
{
temp_sum += root->data + root->Sum ;
return ;
}
else if (k > root->lCount)
{
temp_sum += root->data + root->Sum;
k = k -( root->lCount + 1);
ksmallestElementSumRec(root->right , k , temp_sum);
}
else
ksmallestElementSumRec(root->left , k , temp_sum );
}
int ksmallestElementSum( struct Node *root, int k)
{
int sum = 0;
ksmallestElementSumRec(root, k, sum);
return sum;
}
int main()
{
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
import java.util.*;
class GFG{
static class Node
{
int data;
int lCount;
int Sum ;
Node left;
Node right;
};
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;
}
static Node insert(Node root, int key)
{
if (root == null )
return createNode(key);
if (root.data > key)
{
root.lCount++;
root.Sum += key;
root.left= insert(root.left , key);
}
else if (root.data < key )
root.right= insert (root.right , key );
return root;
}
static int temp_sum;
static void ksmallestElementSumRec(Node root, int k )
{
if (root == null )
return ;
if ((root.lCount + 1 ) == k)
{
temp_sum += root.data + root.Sum ;
return ;
}
else if (k > root.lCount)
{
temp_sum += root.data + root.Sum;
k = k -( root.lCount + 1 );
ksmallestElementSumRec(root.right , k );
}
else
ksmallestElementSumRec(root.left , k );
}
static void ksmallestElementSum(Node root, int k)
{
temp_sum = 0 ;
ksmallestElementSumRec(root, k);
}
public static void main(String[] args)
{
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);
}
}
|
Python3
class createNode:
def __init__( self , data):
self .data = data
self .lCount = 0
self . Sum = 0
self .left = None
self .right = None
def insert(root, key):
if root = = None :
return createNode(key)
if root.data > key:
root.lCount + = 1
root. Sum + = key
root.left = insert(root.left , key)
else if root.data < key:
root.right = insert (root.right , key)
return root
def ksmallestElementSumRec(root, k , temp_sum):
if root = = None :
return
if (root.lCount + 1 ) = = k:
temp_sum[ 0 ] + = root.data + root. Sum
return
else if k > root.lCount:
temp_sum[ 0 ] + = root.data + root. Sum
k = k - ( root.lCount + 1 )
ksmallestElementSumRec(root.right,
k, temp_sum)
else :
ksmallestElementSumRec(root.left,
k, temp_sum)
def ksmallestElementSum(root, k):
Sum = [ 0 ]
ksmallestElementSumRec(root, k, Sum )
return Sum [ 0 ]
if __name__ = = '__main__' :
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))
|
C#
using System;
public class GFG
{
public class Node
{
public int data;
public int lCount;
public int Sum ;
public Node left;
public Node right;
};
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;
}
static Node insert(Node root, int key)
{
if (root == null )
return createNode(key);
if (root.data > key)
{
root.lCount++;
root.Sum += key;
root.left = insert(root.left , key);
}
else if (root.data < key )
root.right = insert (root.right , key );
return root;
}
static int temp_sum;
static void ksmallestElementSumRec(Node root, int k )
{
if (root == null )
return ;
if ((root.lCount + 1) == k)
{
temp_sum += root.data + root.Sum ;
return ;
}
else if (k > root.lCount)
{
temp_sum += root.data + root.Sum;
k = k -( root.lCount + 1);
ksmallestElementSumRec(root.right , k );
}
else
ksmallestElementSumRec(root.left , k );
}
static void ksmallestElementSum(Node root, int k)
{
temp_sum = 0;
ksmallestElementSumRec(root, k);
}
public static void Main(String[] args)
{
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);
}
}
|
Javascript
<script>
class Node {
constructor() {
this .data = 0;
this .lCount = 0;
this .Sum = 0;
this .left = null ;
this .right = null ;
}
}
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;
}
function insert(root, key) {
if (root == null ) return createNode(key);
if (root.data > key) {
root.lCount++;
root.Sum += key;
root.left = insert(root.left, key);
} else if (root.data < key)
root.right = insert(root.right, key);
return root;
}
var temp_sum = 0;
function ksmallestElementSumRec(root, k) {
if (root == null ) return ;
if (root.lCount + 1 == k) {
temp_sum += root.data + root.Sum;
return ;
} else if (k > root.lCount) {
temp_sum += root.data + root.Sum;
k = k - (root.lCount + 1);
ksmallestElementSumRec(root.right, k);
}
else ksmallestElementSumRec(root.left, k);
}
function ksmallestElementSum(root, k) {
temp_sum = 0;
ksmallestElementSumRec(root, k);
}
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>
|
Time Complexity: O(h) where h is height of tree.
Auxiliary Space: O(1)
Playlist : Trees | Data Structures & Algorithms | Programming Tutorials | GeeksforGeeks
If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
14 Feb, 2023
Like Article
Save Article