Sum of k smallest elements in BST
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.
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 BSTstruct 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 ,Sumstruct 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 elementint 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; 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 BSTimport 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 BSTINT_MAX = 2147483647# Binary Tree Node""" utility that allocates a newNodewith 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 ,Sumdef 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 elementdef 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 Codeif __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 BSTusing 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)
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 :





.png)