Sum of k smallest elements in BST
Last Updated :
23 Jul, 2025
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.
Sum of k smallest elements in BST
Similar Reads
Basics & Prerequisites
Data Structures
Getting Started with Array Data StructureArray is a collection of items of the same variable type that are stored at contiguous memory locations. It is one of the most popular and simple data structures used in programming. Basic terminologies of ArrayArray Index: In an array, elements are identified by their indexes. Array index starts fr
14 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem