Sum of k smallest elements in BST
Last Updated :
30 Sep, 2024
Given Binary Search Tree. The task is to find the sum of all elements smaller than and equal to kth smallest element.
Examples:
Input:

Output: 17
Explanation: kth smallest element is 8 so sum of all element smaller than or equal to 8 are 2 + 7 + 8 = 17.
Input:

Output: 25
Explanation: kth smallest element is 8 so sum of all element smaller than or equal to 8 are 8 + 5 + 7 + 2 + 3 = 25.
[Naive Approach] Using Inorder Traversal – O(n) Time and O(n) Space
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.
Below is the implementation of the above approach:
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;
class Node {
public:
int data;
Node *left, *right;
Node(int x) {
data = x;
left = right = nullptr;
}
};
// Recursive function to calculate the sum of the
// first k smallest elements
void calculateSum(Node* root, int& k, int& ans) {
if (root->left != nullptr) {
calculateSum(root->left, k, ans);
}
if (k > 0) {
ans += root->data;
k--;
}
else {
return;
}
if (root->right != nullptr) {
calculateSum(root->right, k, ans);
}
}
// Function to find the sum of the first
// k smallest elements
int sum(Node* root, int k) {
int ans = 0;
calculateSum(root, k, ans);
return ans;
}
int main() {
// Input BST
// 8
// / \
// 7 10
// / / \
// 2 9 13
Node* root = new Node(8);
root->left = new Node(7);
root->right = new Node(10);
root->left->left = new Node(2);
root->right->left = new Node(9);
root->right->right = new Node(13);
int k = 3;
cout << sum(root, k) << "\n";
return 0;
}
C
// C program to find Sum Of All Elements smaller
// than or equal to Kth Smallest Element In BST
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* left;
struct Node* right;
};
// Recursive function to calculate the sum of
// the first k smallest elements
void calculateSum(struct Node* root, int* k, int* ans) {
if (root->left != NULL) {
calculateSum(root->left, k, ans);
}
if (*k > 0) {
*ans += root->data;
(*k)--;
}
else {
return;
}
if (root->right != NULL) {
calculateSum(root->right, k, ans);
}
}
// Function to find the sum of the first
// k smallest elements
int sum(struct Node* root, int k) {
int ans = 0;
calculateSum(root, &k, &ans);
return ans;
}
struct Node* newNode(int data) {
struct Node* node
= (struct Node*)malloc(sizeof(struct Node));
node->data = data;
node->left = node->right = NULL;
return node;
}
int main() {
// Input BST
// 8
// / \
// 7 10
// / / \
// 2 9 13
struct Node* root = newNode(8);
root->left = newNode(7);
root->right = newNode(10);
root->left->left = newNode(2);
root->right->left = newNode(9);
root->right->right = newNode(13);
int k = 3;
printf("%d\n", sum(root, k));
return 0;
}
Java
// Java program to find Sum Of All Elements smaller
// than or equal to Kth Smallest Element In BST
class Node {
int data;
Node left, right;
Node(int x) {
data = x;
left = right = null;
}
}
class GfG {
// Recursive function to calculate the sum of the
// first k smallest elements
static void calculateSum(Node root, int[] k,
int[] ans) {
if (root.left != null) {
calculateSum(root.left, k, ans);
}
if (k[0] > 0) {
ans[0] += root.data;
k[0]--;
}
else {
return;
}
if (root.right != null) {
calculateSum(root.right, k, ans);
}
}
// Function to find the sum of the first
// k smallest elements
static int sum(Node root, int k) {
int[] ans = {0};
int[] kArr = {k};
calculateSum(root, kArr, ans);
return ans[0];
}
public static void main(String[] args) {
// Input BST
// 8
// / \
// 7 10
// / / \
// 2 9 13
Node root = new Node(8);
root.left = new Node(7);
root.right = new Node(10);
root.left.left = new Node(2);
root.right.left = new Node(9);
root.right.right = new Node(13);
int k = 3;
System.out.println(sum(root, k));
}
}
Python
# Python3 program to find Sum Of All
# Elements smaller than or equal to
# Kth Smallest Element In BST
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Recursive function to calculate the sum of
# the first k smallest elements
def calculateSum(root, k, ans):
if root.left is not None:
calculateSum(root.left, k, ans)
if k[0] > 0:
ans[0] += root.data
k[0] -= 1
else:
return
if root.right is not None:
calculateSum(root.right, k, ans)
# Function to find the sum of the first k
# smallest elements
def sum_k_smallest(root, k):
ans = [0]
calculateSum(root, [k], ans)
return ans[0]
if __name__ == "__main__":
# Input BST
# 8
# / \
# 7 10
# / / \
# 2 9 13
root = Node(8)
root.left = Node(7)
root.right = Node(10)
root.left.left = Node(2)
root.right.left = Node(9)
root.right.right = Node(13)
k = 3
print(sum_k_smallest(root, k))
C#
// C# program to find Sum Of All Elements smaller
// than or equal to Kth Smallest Element In BST
using System;
class Node {
public int data;
public Node left, right;
public Node(int data) {
this.data = data;
left = right = null;
}
}
class GfG {
// Recursive function to calculate the sum of
// the first k smallest elements
static void CalculateSum(Node root,
ref int k, ref int ans) {
if (root.left != null) {
CalculateSum(root.left, ref k, ref ans);
}
if (k > 0) {
ans += root.data;
k--;
} else {
return;
}
if (root.right != null) {
CalculateSum(root.right, ref k, ref ans);
}
}
// Function to find the sum of the first k
// smallest elements
static int Sum(Node root, int k) {
int ans = 0;
CalculateSum(root, ref k, ref ans);
return ans;
}
static void Main() {
// Input BST
// 8
// / \
// 7 10
// / / \
// 2 9 13
Node root = new Node(8);
root.left = new Node(7);
root.right = new Node(10);
root.left.left = new Node(2);
root.right.left = new Node(9);
root.right.right = new Node(13);
int k = 3;
Console.WriteLine(Sum(root, k));
}
}
JavaScript
// Javascript program to find Sum Of All Elements smaller
// than or equal to Kth Smallest Element In BST
class Node {
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
}
}
// Recursive function to calculate the sum of the
// first k smallest elements
function calculateSum(root, k, ans) {
if (root.left !== null) {
calculateSum(root.left, k, ans);
}
if (k.val > 0) {
ans.val += root.data;
k.val--;
}
else {
return;
}
if (root.right !== null) {
calculateSum(root.right, k, ans);
}
}
// Function to find the sum of the first k
// smallest elements
function sumKSmallest(root, k) {
let ans = { val: 0 };
let kObj = { val: k };
calculateSum(root, kObj, ans);
return ans.val;
}
// Input BST
// 8
// / \
// 7 10
// / / \
// 2 9 13
let root = new Node(8);
root.left = new Node(7);
root.right = new Node(10);
root.left.left = new Node(2);
root.right.left = new Node(9);
root.right.right = new Node(13);
let k = 3;
console.log(sumKSmallest(root, k));
Time complexity: O(n), where n is the number of nodes in the Binary Search Tree, as the algorithm performs an inorder traversal visiting each node once.
Auxiliary Space: O(h), where h is the height of the tree, due to the recursive call stack. In the worst case (skewed tree), it can be O(n).
[Expected Approach] Using Morris Traversal – O(n) Time and O(1) Space
The idea is to use Morris Traversal , this method establishes temporary threads (links) to allow traversal and reverts these changes afterward to restore the original tree structure. By counting nodes during traversal, we can compute the cumulative sum of the k nodes visited.
Follow the steps below to solve the problem:
- Initialize current as root, and counter, result to store the count and sum of elements found.
- If current has no left child:
- Increment counter and add current’s data to answer.
- If counter == k, return answer.
- Move to the right by updating current as current’right.
- Otherwise:
- Find the rightmost node in current’s left subtree (inorder predecessor) or a node whose right child is current.
- If the right child of the found node is current, restore the original tree:
- Set the right child of the node to NULL, increment counter, add current’s data to answer, and
- if counter == k, return answer.
- Move to the right by updating current as current’right.
- Otherwise, set current as the right child of the rightmost node.
Below is implementation of above approach :
C++
// C++ program to find Sum Of All Elements smaller
// than or equal to Kth Smallest Element In BST
// Using Morris Traversal
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node *left, *right;
Node(int x) {
data = x;
left = right = nullptr;
}
};
// Function to find the sum of all elements
// smaller than or equal to k-th smallest element
int sum(Node *root, int k) {
Node* current = root;
int count = 0, result = 0;
while (current != nullptr) {
if (current->left == nullptr) {
// Visit this node
count++;
result += current->data;
if (count == k) {
return result;
}
// Move to the right subtree
current = current->right;
}
else {
// Find the predecessor
// (rightmost node in left subtree)
Node* pre = current->left;
while (pre->right != nullptr
&& pre->right != current) {
pre = pre->right;
}
if (pre->right == nullptr) {
// Establish thread/link from
// predecessor to current
pre->right = current;
// Move to the left subtree
current = current->left;
}
else {
// Revert the thread/link from
// predecessor to current
pre->right = nullptr;
// Visit this node
count++;
result += current->data;
if (count == k) {
return result;
}
// Move to the right subtree
current = current->right;
}
}
}
return result;
}
int main() {
// Input BST
// 8
// / \
// 7 10
// / / \
// 2 9 13
Node* root = new Node(8);
root->left = new Node(7);
root->right = new Node(10);
root->left->left = new Node(2);
root->right->left = new Node(9);
root->right->right = new Node(13);
int k = 3;
cout << sum(root, k) << "\n";
return 0;
}
C
// C program to find Sum Of All Elements smaller
// than or equal to Kth Smallest Element In BST
// Using Morris Traversal
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *left, *right;
};
// Function to find the sum of all elements
// smaller than or equal to k-th smallest element
int sum(struct Node *root, int k) {
struct Node *current = root;
int count = 0, result = 0;
while (current != NULL) {
if (current->left == NULL) {
// Visit this node
count++;
result += current->data;
if (count == k) {
return result;
}
// Move to the right subtree
current = current->right;
}
else {
// Find the predecessor
// (rightmost node in left subtree)
struct Node *pre = current->left;
while (pre->right != NULL
&& pre->right != current) {
pre = pre->right;
}
if (pre->right == NULL) {
// Establish thread/link from
// predecessor to current
pre->right = current;
// Move to the left subtree
current = current->left;
}
else {
// Revert the thread/link from
// predecessor to current
pre->right = NULL;
// Visit this node
count++;
result += current->data;
if (count == k) {
return result;
}
// Move to the right subtree
current = current->right;
}
}
}
return result;
}
struct Node* createNode(int data) {
struct Node* newNode
= (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
int main() {
// Input BST
// 8
// / \
// 7 10
// / / \
// 2 9 13
struct Node* root = createNode(8);
root->left = createNode(7);
root->right = createNode(10);
root->left->left = createNode(2);
root->right->left = createNode(9);
root->right->right = createNode(13);
int k = 3;
printf("%d\n", sum(root, k));
return 0;
}
Java
// Java program to find Sum Of All Elements smaller
// than or equal to Kth Smallest Element In BST
// Using Morris Traversal
class Node {
int data;
Node left, right;
Node(int x) {
data = x;
left = right = null;
}
}
class GfG {
// Function to find the sum of all elements
// smaller than or equal to k-th smallest element
static int sum(Node root, int k) {
Node current = root;
int count = 0, result = 0;
while (current != null) {
if (current.left == null) {
// Visit this node
count++;
result += current.data;
if (count == k) {
return result;
}
// Move to the right subtree
current = current.right;
}
else {
// Find the predecessor
// (rightmost node in left subtree)
Node pre = current.left;
while (pre.right != null
&& pre.right != current) {
pre = pre.right;
}
if (pre.right == null) {
// Establish thread/link from
// predecessor to current
pre.right = current;
// Move to the left subtree
current = current.left;
}
else {
// Revert the thread/link from
// predecessor to current
pre.right = null;
// Visit this node
count++;
result += current.data;
if (count == k) {
return result;
}
// Move to the right subtree
current = current.right;
}
}
}
return result;
}
public static void main(String[] args) {
// Input BST
// 8
// / \
// 7 10
// / / \
// 2 9 13
Node root = new Node(8);
root.left = new Node(7);
root.right = new Node(10);
root.left.left = new Node(2);
root.right.left = new Node(9);
root.right.right = new Node(13);
int k = 3;
System.out.println(sum(root, k));
}
}
Python
# Python program to find Sum Of All Elements smaller
# than or equal to Kth Smallest Element In BST
# Using Morris Traversal
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Function to find the sum of all elements
# smaller than or equal to k-th smallest element
def sum_kth_smallest(root, k):
current = root
count = 0
result = 0
while current:
if current.left is None:
# Visit this node
count += 1
result += current.data
if count == k:
return result
# Move to the right subtree
current = current.right
else:
# Find the predecessor
# (rightmost node in left subtree)
pre = current.left
while pre.right is not None and pre.right != current:
pre = pre.right
if pre.right is None:
# Establish thread/link from
# predecessor to current
pre.right = current
# Move to the left subtree
current = current.left
else:
# Revert the thread/link from
# predecessor to current
pre.right = None
# Visit this node
count += 1
result += current.data
if count == k:
return result
# Move to the right subtree
current = current.right
return result
if __name__ == "__main__":
# Input BST
# 8
# / \
# 7 10
# / / \
# 2 9 13
root = Node(8)
root.left = Node(7)
root.right = Node(10)
root.left.left = Node(2)
root.right.left = Node(9)
root.right.right = Node(13)
k = 3
print(sum_kth_smallest(root, k))
C#
// C# program to find Sum Of All Elements smaller
// than or equal to Kth Smallest Element In BST
// Using Morris Traversal
using System;
class Node {
public int data;
public Node left, right;
public Node(int x) {
data = x;
left = right = null;
}
}
class GfG {
// Function to find the sum of all elements
// smaller than or equal to k-th smallest element
static int Sum(Node root, int k) {
Node current = root;
int count = 0, result = 0;
while (current != null) {
if (current.left == null) {
// Visit this node
count++;
result += current.data;
if (count == k) {
return result;
}
// Move to the right subtree
current = current.right;
}
else {
// Find the predecessor
// (rightmost node in left subtree)
Node pre = current.left;
while (pre.right != null
&& pre.right != current) {
pre = pre.right;
}
if (pre.right == null) {
// Establish thread/link from
// predecessor to current
pre.right = current;
// Move to the left subtree
current = current.left;
}
else {
// Revert the thread/link from
// predecessor to current
pre.right = null;
// Visit this node
count++;
result += current.data;
if (count == k) {
return result;
}
// Move to the right subtree
current = current.right;
}
}
}
return result;
}
static void Main(string[] args) {
// Input BST
// 8
// / \
// 7 10
// / / \
// 2 9 13
Node root = new Node(8);
root.left = new Node(7);
root.right = new Node(10);
root.left.left = new Node(2);
root.right.left = new Node(9);
root.right.right = new Node(13);
int k = 3;
Console.WriteLine(Sum(root, k));
}
}
JavaScript
// JavaScript program to find Sum Of All Elements
// smaller than or equal to Kth Smallest
// Element In BST Using Morris Traversal
class Node {
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
}
}
// Function to find the sum of all elements
// smaller than or equal to k-th smallest element
function sum(root, k) {
let current = root;
let count = 0;
let result = 0;
while (current !== null) {
if (current.left === null) {
// Visit this node
count++;
result += current.data;
if (count === k) {
return result;
}
// Move to the right subtree
current = current.right;
}
else {
// Find the predecessor (rightmost node in left subtree)
let pre = current.left;
while (pre.right !== null && pre.right !== current) {
pre = pre.right;
}
if (pre.right === null) {
// Establish thread/link from predecessor to current
pre.right = current;
// Move to the left subtree
current = current.left;
}
else {
// Revert the thread/link from predecessor to current
pre.right = null;
// Visit this node
count++;
result += current.data;
if (count === k) {
return result;
}
// Move to the right subtree
current = current.right;
}
}
}
return result;
}
// Input BST
// 8
// / \
// 7 10
// / / \
// 2 9 13
let root = new Node(8);
root.left = new Node(7);
root.right = new Node(10);
root.left.left = new Node(2);
root.right.left = new Node(9);
root.right.right = new Node(13);
let k = 3;
console.log(sum(root, k));
Time Complexity: O(k), since we only traverse the tree until the k-th smallest element.
Auxiliary Space: O(1), for the iterative approach, as it uses a constant amount of space, with no additional data structures aside from a few variables.
Similar Reads
Binary Search Tree
A Binary Search Tree (or BST) is a data structure used in computer science for organizing and storing data in a sorted manner. Each node in a Binary Search Tree has at most two children, a left child and a right child, with the left child containing values less than the parent node and the right chi
3 min read
Introduction to Binary Search Tree
Binary Search Tree is a data structure used in computer science for organizing and storing data in a sorted manner. Binary search tree follows all properties of binary tree and for every nodes, its left subtree contains values less than the node and the right subtree contains values greater than the
3 min read
Applications of BST
Binary Search Tree (BST) is a data structure that is commonly used to implement efficient searching, insertion, and deletion operations along with maintaining sorted sequence of data. Please remember the following properties of BSTs before moving forward. The left subtree of a node contains only nod
2 min read
Applications, Advantages and Disadvantages of Binary Search Tree
A Binary Search Tree (BST) is a data structure used to storing data in a sorted manner. Each node in a Binary Search Tree has at most two children, a left child and a right child, with the left child containing values less than the parent node and the right child containing values greater than the p
2 min read
Insertion in Binary Search Tree (BST)
Given a BST, the task is to insert a new node in this BST. Example: How to Insert a value in a Binary Search Tree:A new key is always inserted at the leaf by maintaining the property of the binary search tree. We start searching for a key from the root until we hit a leaf node. Once a leaf node is f
15+ min read
Searching in Binary Search Tree (BST)
Given a BST, the task is to search a node in this BST. For searching a value in BST, consider it as a sorted array. Now we can easily perform search operation in BST using Binary Search Algorithm. Input: Root of the below BST Output: TrueExplanation: 8 is present in the BST as right child of rootInp
7 min read
Deletion in Binary Search Tree (BST)
Given a BST, the task is to delete a node in this BST, which can be broken down into 3 scenarios: Case 1. Delete a Leaf Node in BST Case 2. Delete a Node with Single Child in BST Deleting a single child node is also simple in BST. Copy the child to the node and delete the node. Case 3. Delete a Node
10 min read
Binary Search Tree (BST) Traversals â Inorder, Preorder, Post Order
Given a Binary Search Tree, The task is to print the elements in inorder, preorder, and postorder traversal of the Binary Search Tree. Input: Output: Inorder Traversal: 10 20 30 100 150 200 300Preorder Traversal: 100 20 10 30 200 150 300Postorder Traversal: 10 30 20 150 300 200 100 Input: Output:
11 min read
Balance a Binary Search Tree
Given a BST (Binary Search Tree) that may be unbalanced, the task is to convert it into a balanced BST that has the minimum possible height. Examples: Input: Output: Explanation: The above unbalanced BST is converted to balanced with the minimum possible height. Input: Output: Explanation: The above
10 min read
Self-Balancing Binary Search Trees
Self-Balancing Binary Search Trees are height-balanced binary search trees that automatically keep the height as small as possible when insertion and deletion operations are performed on the tree. The height is typically maintained in order of logN so that all operations take O(logN) time on average
4 min read