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.
Method 1: Using Inorder Traversal (O(n) time and O(h) auxiliary space)
The Inorder Traversal of a BST traverses the nodes in increasing order. So the idea is to traverse the tree in Inorder. While traversing, keep track of the count of the nodes visited. If the count becomes k, print the node.
C++
// A simple inorder traversal based C++ program to find k-th
// smallest element in a BST.
#include <iostream>
usingnamespacestd;
// A BST node
structNode {
intdata;
Node *left, *right;
Node(intx)
{
data = x;
left = right = NULL;
}
};
// Recursive function to insert an key into BST
Node* insert(Node* root, intx)
{
if(root == NULL)
returnnewNode(x);
if(x < root->data)
root->left = insert(root->left, x);
elseif(x > root->data)
root->right = insert(root->right, x);
returnroot;
}
// Function to find k'th smallest element in BST
// Here count denotes the number of nodes processed so far
intcount = 0;
Node* kthSmallest(Node* root, int& k)
{
// base case
if(root == NULL)
returnNULL;
// search in left subtree
Node* left = kthSmallest(root->left, k);
// if k'th smallest is found in left subtree, return it
if(left != NULL)
returnleft;
// if current element is k'th smallest, return it
count++;
if(count == k)
returnroot;
// else search in right subtree
returnkthSmallest(root->right, k);
}
// Function to print k'th smallest element in BST
voidprintKthSmallest(Node* root, intk)
{
// maintain index to count number of nodes processed so far
Node* res = kthSmallest(root, k);
if(res == NULL)
cout << "There are less than k nodes in the BST";
else
cout << "K-th Smallest Element is "<< res->data;
}
// main function
intmain()
{
Node* root = NULL;
intkeys[] = { 20, 8, 22, 4, 12, 10, 14 };
for(intx : keys)
root = insert(root, x);
intk = 3;
printKthSmallest(root, k);
return0;
}
// This code is contributed by Aditya Kumar (adityakumar129)
C
// A simple inorder traversal based C++ program to find k-th
// smallest element in a BST.
#include <stdio.h>
#include <stdlib.h>
// A BST node
typedefstructNode {
intdata;
structNode *left, *right;
} Node;
structNode* new_node(intx)
{
structNode* p = malloc(sizeof(structNode));
p->data = x;
p->left = NULL;
p->right = NULL;
returnp;
}
// Recursive function to insert an key into BST
Node* insert(Node* root, intx)
{
if(root == NULL)
returnnew_node(x);
if(x < root->data)
root->left = insert(root->left, x);
elseif(x > root->data)
root->right = insert(root->right, x);
returnroot;
}
// Function to find k'th smallest element in BST
// Here count denotes the number of nodes processed so far
intcount = 0;
Node* kthSmallest(Node* root, intk)
{
// base case
if(root == NULL)
returnNULL;
// search in left subtree
Node* left = kthSmallest(root->left, k);
// if k'th smallest is found in left subtree, return it
if(left != NULL)
returnleft;
// if current element is k'th smallest, return it
count++;
if(count == k)
returnroot;
// else search in right subtree
returnkthSmallest(root->right, k);
}
// Function to print k'th smallest element in BST
voidprintKthSmallest(Node* root, intk)
{
// maintain index to count number of nodes processed so far
Node* res = kthSmallest(root, k);
if(res == NULL)
printf("There are less than k nodes in the BST");
else
printf("K-th Smallest Element is %d", res->data);
}
// main function
intmain()
{
Node* root = NULL;
intkeys[] = { 20, 8, 22, 4, 12, 10, 14 };
intkeys_size = sizeof(keys) / sizeof(keys[0]);
for(inti = 0; i < keys_size; i++)
root = insert(root, keys[i]);
intk = 3;
printKthSmallest(root, k);
return0;
}
// This code is contributed by Aditya Kumar (adityakumar129)
Java
// A simple inorder traversal based Java program
// to find k-th smallest element in a BST.
importjava.io.*;
// A BST node
classNode {
intdata;
Node left, right;
Node(intx)
{
data = x;
left = right = null;
}
}
classGFG {
staticintcount = 0;
// Recursive function to insert an key into BST
publicstaticNode insert(Node root, intx)
{
if(root == null)
returnnewNode(x);
if(x < root.data)
root.left = insert(root.left, x);
elseif(x > root.data)
root.right = insert(root.right, x);
returnroot;
}
// Function to find k'th smallest element in BST
// Here count denotes the number of nodes processed so far
publicstaticNode kthSmallest(Node root, intk)
{
// base case
if(root == null)
returnnull;
// search in left subtree
Node left = kthSmallest(root.left, k);
// if k'th smallest is found in left subtree, return it
if(left != null)
returnleft;
// if current element is k'th smallest, return it
count++;
if(count == k)
returnroot;
// else search in right subtree
returnkthSmallest(root.right, k);
}
// Function to find k'th smallest element in BST
publicstaticvoidprintKthSmallest(Node root, intk)
{
Node res = kthSmallest(root, k);
if(res == null)
System.out.println("There are less than k nodes in the BST");
else
System.out.println("K-th Smallest Element is "+ res.data);
}
publicstaticvoidmain(String[] args)
{
Node root = null;
intkeys[] = { 20, 8, 22, 4, 12, 10, 14};
for(intx : keys)
root = insert(root, x);
intk = 3;
printKthSmallest(root, k);
}
}
// This code is contributed by Aditya Kumar (adityakumar129)
Python3
# A simple inorder traversal based Python3
# program to find k-th smallest element
# in a BST.
# A BST node
classNode:
def__init__(self, key):
self.data =key
self.left =None
self.right =None
# Recursive function to insert an key into BST
definsert(root, x):
if(root ==None):
returnNode(x)
if(x < root.data):
root.left =insert(root.left, x)
elif(x > root.data):
root.right =insert(root.right, x)
returnroot
# Function to find k'th largest element
# in BST. Here count denotes the number
# of nodes processed so far
defkthSmallest(root):
globalk
# Base case
if(root ==None):
returnNone
# Search in left subtree
left =kthSmallest(root.left)
# If k'th smallest is found in
# left subtree, return it
if(left !=None):
returnleft
# If current element is k'th
# smallest, return it
k -=1
if(k ==0):
returnroot
# Else search in right subtree
returnkthSmallest(root.right)
# Function to find k'th largest element in BST
defprintKthSmallest(root):
res =kthSmallest(root)
if(res ==None):
print("There are less than k nodes in the BST")
else:
print("K-th Smallest Element is ", res.data)
# Driver code
if__name__ =='__main__':
root =None
keys =[20, 8, 22, 4, 12, 10, 14]
forx inkeys:
root =insert(root, x)
k =3
printKthSmallest(root)
# This code is contributed by mohit kumar 29
C#
// A simple inorder traversal
// based C# program to find
// k-th smallest element in a BST.
usingSystem;
// A BST node
classNode{
publicintdata;
publicNode left, right;
publicNode(intx)
{
data = x;
left = right = null;
}
}
classGFG{
staticintcount = 0;
// Recursive function to
// insert an key into BST
publicstaticNode insert(Node root,
intx)
{
if(root == null)
returnnewNode(x);
if(x < root.data)
root.left = insert(root.left, x);
elseif(x > root.data)
root.right = insert(root.right, x);
returnroot;
}
// Function to find k'th largest
// element in BST. Here count
// denotes the number of nodes
// processed so far
publicstaticNode kthSmallest(Node root,
intk)
{
// base case
if(root == null)
returnnull;
// search in left subtree
Node left = kthSmallest(root.left, k);
// if k'th smallest is found
// in left subtree, return it
if(left != null)
returnleft;
// if current element is
// k'th smallest, return it
count++;
if(count == k)
returnroot;
// else search in right subtree
returnkthSmallest(root.right, k);
}
// Function to find k'th largest
// element in BST
publicstaticvoidprintKthSmallest(Node root,
intk)
{
// Maintain an index to
// count number of nodes
// processed so far
count = 0;
Node res = kthSmallest(root, k);
if(res == null)
Console.WriteLine("There are less "+
"than k nodes in the BST");
else
Console.WriteLine("K-th Smallest"+
" Element is "+ res.data);
}
// Driver code
publicstaticvoidMain(String[] args)
{
Node root = null;
int[]keys = {20, 8, 22, 4,
12, 10, 14};
foreach(intx inkeys)
root = insert(root, x);
intk = 3;
printKthSmallest(root, k);
}
}
// This code is contributed by gauravrajput1
Javascript
<script>
// A simple inorder traversal based Javascript program
// to find k-th smallest element in a BST.
// A BST node
class Node
{
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}
}
let count = 0;
// Recursive function to insert an key into BST
functioninsert(root,x)
{
if(root == null)
returnnewNode(x);
if(x < root.data)
root.left = insert(root.left, x);
elseif(x > root.data)
root.right = insert(root.right, x);
returnroot;
}
// Function to find k'th largest element in BST
// Here count denotes the number
// of nodes processed so far
functionkthSmallest(root,k)
{
// base case
if(root == null)
returnnull;
// search in left subtree
let left = kthSmallest(root.left, k);
// if k'th smallest is found in left subtree, return it
if(left != null)
returnleft;
// if current element is k'th smallest, return it
count++;
if(count == k)
returnroot;
// else search in right subtree
returnkthSmallest(root.right, k);
}
// Function to find k'th largest element in BST
functionprintKthSmallest(root,k)
{
// maintain an index to count number of
// nodes processed so far
count = 0;
let res = kthSmallest(root, k);
if(res == null)
document.write("There are less "
+ "than k nodes in the BST");
else
document.write("K-th Smallest"
+ " Element is "+ res.data);
}
let root=null;
let key=[20, 8, 22, 4, 12, 10, 14 ];
for(let i=0;i<key.length;i++)
{
root = insert(root, key[i]);
}
let k = 3;
printKthSmallest(root, k);
// This code is contributed by unknown2108
</script>
Output
K-th Smallest Element is 10
Time complexity: O(n) where n is the number of nodes in a binary search tree. Auxiliary Space: O(h) where h is the height of the binary search tree.
Method 2: Using Any Tree Traversal (pre-in-post) than return kth smallest easily.
Approach:
Here we use pre order traversal than sort it and return the kth smallest element.
Algorithm:
Here we have tree we will take preorder of it as :
preorder will : 20 8 4 12 10 14 22
And store it in array/vector.
After taking preorder we will sort it and than return k-1 element from the array.
C++
// A simple inorder traversal based C++ program to find k-th
// smallest element in a BST.
#include <iostream>
#include <bits/stdc++.h>
usingnamespacestd;
// A BST node
structNode {
intdata;
Node *left, *right;
intlCount;
Node(intx)
{
data = x;
left = right = NULL;
lCount = 0;
}
};
// Recursive function to insert an key into BST
Node* insert(Node* root, intx)
{
if(root == NULL)
returnnewNode(x);
// If a node is inserted in left subtree, then lCount of
// this node is increased. For simplicity, we are
// assuming that all keys (tried to be inserted) are
// distinct.
if(x < root->data) {
root->left = insert(root->left, x);
root->lCount++;
}
elseif(x > root->data)
root->right = insert(root->right, x);
returnroot;
}
//preorder function.
voidpreorder(Node* root,vector<int>&v){
if(root==NULL)return;
v.push_back(root->data);
preorder(root->left,v);
preorder(root->right,v);
}
intmain(){
Node* root = NULL;
intkeys[] = { 20, 8, 22, 4, 12, 10, 14 };
for(intx : keys)
root = insert(root, x);
intk = 4;
vector<int>v;
preorder(root,v);
//for(auto it:v)cout<<it<<" ";
// cout<<endl;
//sorting the given vector.
sort(v.begin(),v.end());
//return kth smallest element.
cout<<v[k-1]<<endl;
//code and approach contributed by Sanket Gode.
return0;
}
Java
importjava.util.*;
classNode {
intdata;
Node left, right;
intlCount;
Node(intx) {
data = x;
left = right = null;
lCount = 0;
}
}
publicclassKthSmallestElementBST {
// Recursive function to insert a key into BST
staticNode insert(Node root, intx) {
if(root == null)
returnnewNode(x);
// If a node is inserted in left subtree, then lCount of
// this node is increased. For simplicity, we are
// assuming that all keys (tried to be inserted) are
// distinct.
if(x < root.data) {
root.left = insert(root.left, x);
root.lCount++;
}
elseif(x > root.data)
root.right = insert(root.right, x);
returnroot;
}
// Preorder traversal of BST
staticvoidpreorder(Node root, List<Integer> v) {
if(root == null) return;
v.add(root.data);
preorder(root.left, v);
preorder(root.right, v);
}
publicstaticvoidmain(String[] args) {
Node root = null;
int[] keys = { 20, 8, 22, 4, 12, 10, 14};
for(intx : keys)
root = insert(root, x);
intk = 4;
List<Integer> v = newArrayList<Integer>();
preorder(root, v);
// Sorting the given vector
Collections.sort(v);
// Finding kth smallest element
System.out.println(v.get(k-1));
}
}
Python3
# A BST node
classNode:
def__init__(self, x):
self.data =x
self.left =None
self.right =None
self.lCount =0
# Recursive function to insert a key into BST
definsert(root, x):
ifroot isNone:
returnNode(x)
# If a node is inserted in the left subtree, then lCount of
# this node is increased. For simplicity, we are
# assuming that all keys (tried to be inserted) are
# distinct.
ifx < root.data:
root.left =insert(root.left, x)
root.lCount +=1
elifx > root.data:
root.right =insert(root.right, x)
returnroot
# Preorder traversal function
defpreorder(root, v):
ifroot isNone:
return
v.append(root.data)
preorder(root.left, v)
preorder(root.right, v)
# Main function
if__name__ =='__main__':
root =None
keys =[20, 8, 22, 4, 12, 10, 14]
forx inkeys:
root =insert(root, x)
k =4
v =[]
preorder(root, v)
# Sorting the given list
v.sort()
# Return the kth smallest element
print(v[k-1])
C#
usingSystem;
usingSystem.Collections.Generic;
classProgram
{
// A BST node
classNode
{
publicintdata;
publicNode left, right;
publicintlCount;
publicNode(intx)
{
data = x;
left = right = null;
lCount = 0;
}
}
// Recursive function to insert an key into BST
staticNode insert(Node root, intx)
{
if(root == null)
returnnewNode(x);
// If a node is inserted in left subtree, then lCount of
// this node is increased. For simplicity, we are
// assuming that all keys (tried to be inserted) are
// distinct.
if(x < root.data)
{
root.left = insert(root.left, x);
root.lCount++;
}
elseif(x > root.data)
{
root.right = insert(root.right, x);
}
returnroot;
}
// Inorder traversal to get sorted order
staticvoidinorder(Node root, List<int> v)
{
if(root == null) return;
inorder(root.left, v);
v.Add(root.data);
inorder(root.right, v);
}
staticvoidMain(string[] args)
{
Node root = null;
int[] keys = { 20, 8, 22, 4, 12, 10, 14 };
foreach(intx inkeys)
{
root = insert(root, x);
}
intk = 4;
List<int> v = newList<int>();
inorder(root, v);
// k-th smallest element is at index k-1 in the sorted array
Console.WriteLine(v[k - 1]);
}
}
Javascript
class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
this.lCount = 0;
}
}
functioninsert(root, x) {
if(root === null) {
returnnewNode(x);
}
if(x < root.data) {
root.left = insert(root.left, x);
root.lCount++;
} elseif(x > root.data) {
root.right = insert(root.right, x);
}
returnroot;
}
functionpreorder(root, v) {
if(root === null) {
return;
}
v.push(root.data);
preorder(root.left, v);
preorder(root.right, v);
}
let root = null;
const keys = [20, 8, 22, 4, 12, 10, 14];
for(const x of keys) {
root = insert(root, x);
}
const k = 4;
const v = [];
preorder(root, v);
v.sort((a, b) => a - b);
console.log(v[k - 1]);
Output
12
Complexity Analysis:
Time Complexity: O(nlogn) i.e O(n) time for preorder and nlogn time for sorting. Auxiliary Space: O(n) i.e for vector/array storage.
Method 3: Augmented Tree Data Structure (O(h) Time Complexity and O(h) auxiliary space)
The idea is to maintain the rank of each node. We can keep track of elements in the left subtree of every node while building the tree. Since we need the K-th smallest element, we can maintain the number of elements of the left subtree in every node. Assume that the root is having ‘lCount’ nodes in its left subtree. If K = lCount + 1, root is K-th node. If K < lCount + 1, we will continue our search (recursion) for the Kth smallest element in the left subtree of root. If K > lCount + 1, we continue our search in the right subtree for the (K – lCount – 1)-th smallest element. Note that we need the count of elements in the left subtree only.
C++
// A simple inorder traversal based C++ program to find k-th
// smallest element in a BST.
#include <iostream>
usingnamespacestd;
// A BST node
structNode {
intdata;
Node *left, *right;
intlCount;
Node(intx)
{
data = x;
left = right = NULL;
lCount = 0;
}
};
// Recursive function to insert an key into BST
Node* insert(Node* root, intx)
{
if(root == NULL)
returnnewNode(x);
// If a node is inserted in left subtree, then lCount of
// this node is increased. For simplicity, we are
// assuming that all keys (tried to be inserted) are
// distinct.
if(x < root->data) {
root->left = insert(root->left, x);
root->lCount++;
}
elseif(x > root->data)
root->right = insert(root->right, x);
returnroot;
}
// Function to find k'th smallest element in BST
// Here count denotes the number of nodes processed so far
Node* kthSmallest(Node* root, intk)
{
// base case
if(root == NULL)
returnNULL;
intcount = root->lCount + 1;
if(count == k)
returnroot;
if(count > k)
returnkthSmallest(root->left, k);
// else search in right subtree
returnkthSmallest(root->right, k - count);
}
// main function
intmain()
{
Node* root = NULL;
intkeys[] = { 20, 8, 22, 4, 12, 10, 14 };
for(intx : keys)
root = insert(root, x);
intk = 4;
Node* res = kthSmallest(root, k);
if(res == NULL)
cout << "There are less than k nodes in the BST";
else
cout << "K-th Smallest Element is "<< res->data;
return0;
}
// This code is contributed by Aditya Kumar (adityakumar129)
C
// A simple inorder traversal based C++ program to find k-th
// smallest element in a BST.
#include <stdio.h>
#include <stdlib.h>
// A BST node
typedefstructNode {
intdata;
structNode *left, *right;
intlCount;
} Node;
Node* new_node(intx)
{
Node* newNode = malloc(sizeof(Node));
newNode->data = x;
newNode->left = NULL;
newNode->right = NULL;
returnnewNode;
}
// Recursive function to insert an key into BST
Node* insert(Node* root, intx)
{
if(root == NULL)
returnnew_node(x);
// If a node is inserted in left subtree, then lCount of
// this node is increased. For simplicity, we are
// assuming that all keys (tried to be inserted) are
// distinct.
if(x < root->data) {
root->left = insert(root->left, x);
root->lCount++;
}
elseif(x > root->data)
root->right = insert(root->right, x);
returnroot;
}
// Function to find k'th smallest element in BST
// Here count denotes the number of nodes processed so far
Node* kthSmallest(Node* root, intk)
{
// base case
if(root == NULL)
returnNULL;
intcount = root->lCount + 1;
if(count == k)
returnroot;
if(count > k)
returnkthSmallest(root->left, k);
// else search in right subtree
returnkthSmallest(root->right, k - count);
}
// main function
intmain()
{
Node* root = NULL;
intkeys[] = { 20, 8, 22, 4, 12, 10, 14 };
intkeys_size = sizeof(keys) / sizeof(keys[0]);
for(inti = 0; i < keys_size; i++)
root = insert(root, keys[i]);
intk = 4;
Node* res = kthSmallest(root, k);
if(res == NULL)
printf("There are less than k nodes in the BST");
else
printf("K-th Smallest Element is %d", res->data);
return0;
}
// This code is contributed by Aditya Kumar (adityakumar129)
Java
// A simple inorder traversal based Java program
// to find k-th smallest element in a BST.
importjava.io.*;
importjava.util.*;
// A BST node
classNode {
intdata;
Node left, right;
intlCount;
Node(intx)
{
data = x;
left = right = null;
lCount = 0;
}
}
classGfg {
// Recursive function to insert an key into BST
publicstaticNode insert(Node root, intx)
{
if(root == null)
returnnewNode(x);
// If a node is inserted in left subtree, then
// lCount of this node is increased. For simplicity,
// we are assuming that all keys (tried to be
// inserted) are distinct.
if(x < root.data) {
root.left = insert(root.left, x);
root.lCount++;
}
elseif(x > root.data)
root.right = insert(root.right, x);
returnroot;
}
// Function to find k'th largest element in BST
// Here count denotes the number of nodes processed so far
publicstaticNode kthSmallest(Node root, intk)
{
// base case
if(root == null)
returnnull;
intcount = root.lCount + 1;
if(count == k)
returnroot;
if(count > k)
returnkthSmallest(root.left, k);
// else search in right subtree
returnkthSmallest(root.right, k - count);
}
// main function
publicstaticvoidmain(String args[])
{
Node root = null;
intkeys[] = { 20, 8, 22, 4, 12, 10, 14};
for(intx : keys)
root = insert(root, x);
intk = 4;
Node res = kthSmallest(root, k);
if(res == null)
System.out.println("There are less than k nodes in the BST");
else
System.out.println("K-th Smallest Element is "+ res.data);
}
}
// This code is contributed by Aditya Kumar (adityakumar129)
Python3
# A simple inorder traversal based Python3
# program to find k-th smallest element in a BST.
# A BST node
classnewNode:
def__init__(self, x):
self.data =x
self.left =None
self.right =None
self.lCount =0
# Recursive function to insert
# an key into BST
definsert(root, x):
if(root ==None):
returnnewNode(x)
# If a node is inserted in left subtree,
# then lCount of this node is increased.
# For simplicity, we are assuming that
# all keys (tried to be inserted) are
# distinct.
if(x < root.data):
root.left =insert(root.left, x)
root.lCount +=1
elif(x > root.data):
root.right =insert(root.right, x);
returnroot
# Function to find k'th largest element
# in BST. Here count denotes the number
# of nodes processed so far
defkthSmallest(root, k):
# Base case
if(root ==None):
returnNone
count =root.lCount +1
if(count ==k):
returnroot
if(count > k):
returnkthSmallest(root.left, k)
# Else search in right subtree
returnkthSmallest(root.right, k -count)
# Driver code
if__name__ =='__main__':
root =None
keys =[ 20, 8, 22, 4, 12, 10, 14]
forx inkeys:
root =insert(root, x)
k =4
res =kthSmallest(root, k)
if(res ==None):
print("There are less than k nodes in the BST")
else:
print("K-th Smallest Element is", res.data)
# This code is contributed by bgangwar59
C#
// A simple inorder traversal based C# program
// to find k-th smallest element in a BST.
usingSystem;
// A BST node
publicclassNode
{
publicintdata;
publicNode left, right;
publicintlCount;
publicNode(intx)
{
data = x;
left = right = null;
lCount = 0;
}
}
classGFG{
// Recursive function to insert an key into BST
publicstaticNode insert(Node root, intx)
{
if(root == null)
returnnewNode(x);
// If a node is inserted in left subtree,
// then lCount of this node is increased.
// For simplicity, we are assuming that
// all keys (tried to be inserted) are
// distinct.
if(x < root.data)
{
root.left = insert(root.left, x);
root.lCount++;
}
elseif(x > root.data)
root.right = insert(root.right, x);
returnroot;
}
// Function to find k'th largest element
// in BST. Here count denotes the number
// of nodes processed so far
publicstaticNode kthSmallest(Node root, intk)
{
// Base case
if(root == null)
returnnull;
intcount = root.lCount + 1;
if(count == k)
returnroot;
if(count > k)
returnkthSmallest(root.left, k);
// Else search in right subtree
returnkthSmallest(root.right, k - count);
}
// Driver Code
publicstaticvoidMain(String[] args)
{
Node root = null;
int[] keys = { 20, 8, 22, 4, 12, 10, 14 };
foreach(intx inkeys)
root = insert(root, x);
intk = 4;
Node res = kthSmallest(root, k);
if(res == null)
Console.WriteLine("There are less "+
"than k nodes in the BST");
else
Console.WriteLine("K-th Smallest"+
" Element is "+ res.data);
}
}
// This code is contributed by aashish1995
Javascript
<script>
// A simple inorder traversal based
// Javascript program to find k-th
// smallest element in a BST.
// A BST node
class Node
{
constructor(x)
{
this.data = x;
this.left = null;
this.right = null;
this.lCount = 0;
}
}
// Recursive function to insert an key into BST
functioninsert(root, x)
{
if(root == null)
returnnewNode(x);
// If a node is inserted in left subtree,
// then lCount of this node is increased.
// For simplicity, we are assuming that
// all keys (tried to be inserted) are
// distinct.
if(x < root.data)
{
root.left = insert(root.left, x);
root.lCount++;
}
elseif(x > root.data)
root.right = insert(root.right, x);
returnroot;
}
// Function to find k'th largest element
// in BST. Here count denotes the number
// of nodes processed so far
functionkthSmallest(root, k)
{
// Base case
if(root == null)
returnnull;
let count = root.lCount + 1;
if(count == k)
returnroot;
if(count > k)
returnkthSmallest(root.left, k);
// Else search in right subtree
returnkthSmallest(root.right, k - count);
}
// Driver code
let root = null;
let keys = [ 20, 8, 22, 4, 12, 10, 14 ];
for(let x = 0; x < keys.length; x++)
root = insert(root, keys[x]);
let k = 4;
let res = kthSmallest(root, k);
if(res == null)
document.write("There are less than k "+
"nodes in the BST"+ "</br>");
else
document.write("K-th Smallest"+
" Element is "+ res.data);
// This code is contributed by divyeshrabadiya07
</script>
Output
K-th Smallest Element is 12
Time complexity: O(h) where h is the height of the tree. Auxiliary Space: O(h)
Method 4: Iterative approach using Stack: The basic idea behind the Iterative Approach using Stack to find the kth smallest element in a Binary Search Tree (BST) is to traverse the tree in an inorder fashion using a stack until we find the kth smallest element. Follow the steps to implement the above idea:
Create an empty stack and set the current node to the root of the BST.
Push all the left subtree nodes of the current node onto the stack until the current node is NULL.
Pop the top node from the stack and check if it is the k-th element. If it is, return its value.
Decrement the value of k by 1.
Set the current node to the right child of the popped node.
Go to step 2 if the stack is not empty or k is not equal to 0.
Below is the implementation of the above approach:
C++
// C++ code to implement the iterative approach
#include <iostream>
#include <stack>
usingnamespacestd;
// Definition of a BST node
structNode {
intdata;
Node *left, *right;
};
// Function to create a new BST node
Node* newNode(intkey)
{
Node* node = newNode;
node->data = key;
node->left = node->right = NULL;
returnnode;
}
// Function to insert a new node in BST
Node* insert(Node* root, intkey)
{
// If the tree is empty, return a new node
if(root == NULL)
returnnewNode(key);
// Otherwise, recur down the tree
if(key < root->data)
root->left = insert(root->left, key);
elseif(key > root->data)
root->right = insert(root->right, key);
// Return the (unchanged) node pointer
returnroot;
}
// Function to find the k-th smallest
// element in BST
intkthSmallest(Node* root, intk)
{
// Create an empty stack
stack<Node*> s;
// Loop until stack is empty or
// k becomes zero
while(root != NULL || !s.empty()) {
// Push all the left subtree
// nodes onto the stack
while(root != NULL) {
s.push(root);
root = root->left;
}
// Pop the top node from the
// stack and check if it is
// the k-th element
root = s.top();
s.pop();
if(--k == 0)
returnroot->data;
// Set root to the right child
// and continue with the traversal
root = root->right;
}
// If k is greater than the number
// of nodes in BST, return -1
return-1;
}
// Driver Code
intmain()
{
Node* root = NULL;
intkeys[] = { 20, 8, 22, 4, 12, 10, 14 };
// Insert all the keys into BST
for(intx : keys)
root = insert(root, x);
intk = 4;
// Find the k-th smallest element in BST
intkth_smallest = kthSmallest(root, k);
if(kth_smallest != -1)
cout << "K-th smallest element in BST is: "
<< kth_smallest << endl;
else
cout << "Invalid input"<< endl;
return0;
}
Java
importjava.util.Stack;
classNode {
intdata;
Node left, right;
Node(intkey) {
data = key;
left = right = null;
}
}
classGFG {
staticNode insert(Node root, intkey) {
if(root == null)
returnnewNode(key);
if(key < root.data)
root.left = insert(root.left, key);
elseif(key > root.data)
root.right = insert(root.right, key);
returnroot;
}
staticintkthSmallest(Node root, intk) {
Stack<Node> stack = newStack<>();
while(root != null|| !stack.empty()) {
while(root != null) {
stack.push(root);
root = root.left;
}
root = stack.pop();
if(--k == 0)
returnroot.data;
root = root.right;
}
return-1;
}
publicstaticvoidmain(String[] args) {
Node root = null;
int[] keys = { 20, 8, 22, 4, 12, 10, 14};
for(intx : keys)
root = insert(root, x);
intk = 4;
intkth_smallest = kthSmallest(root, k);
if(kth_smallest != -1)
System.out.println("K-th smallest element in BST is: "+ kth_smallest);
else
System.out.println("Invalid input");
}
}
Python3
# Python code to implement the iterative approach
# Definition of a BST node
classNode:
def__init__(self, key):
self.data =key
self.left =None
self.right =None
# Function to insert a new node in BST
definsert(root, key):
# If the tree is empty, return a new node
ifroot isNone:
returnNode(key)
# Otherwise, recur down the tree
ifkey < root.data:
root.left =insert(root.left, key)
elifkey > root.data:
root.right =insert(root.right, key)
# Return the (unchanged) node pointer
returnroot
# Function to find the k-th smallest
# element in BST
defkthSmallest(root, k):
# Create an empty stack
stack =[]
# Loop until stack is empty or
# k becomes zero
whileroot isnotNoneorlen(stack) > 0:
# Push all the left subtree
# nodes onto the stack
whileroot isnotNone:
stack.append(root)
root =root.left
# Pop the top node from the
# stack and check if it is
# the k-th element
root =stack.pop()
k -=1
ifk ==0:
returnroot.data
# Set root to the right child
# and continue with the traversal
root =root.right
# If k is greater than the number
# of nodes in BST, return -1
return-1
# Driver Code
if__name__ =='__main__':
root =None
keys =[20, 8, 22, 4, 12, 10, 14]
# Insert all the keys into BST
forx inkeys:
root =insert(root, x)
k =4
# Find the k-th smallest element in BST
kth_smallest =kthSmallest(root, k)
ifkth_smallest !=-1:
print("K-th smallest element in BST is:", kth_smallest)
else:
print("Invalid input")
C#
usingSystem;
usingSystem.Collections.Generic;
// Definition of a BST node
publicclassNode
{
publicintdata;
publicNode left, right;
publicNode(intkey)
{
data = key;
left = right = null;
}
}
publicclassBinarySearchTree
{
// Function to insert a new node in BST
publicstaticNode Insert(Node root, intkey)
{
// If the tree is empty, return a new node
if(root == null)
returnnewNode(key);
// Otherwise, recur down the tree
if(key < root.data)
root.left = Insert(root.left, key);
elseif(key > root.data)
root.right = Insert(root.right, key);
// Return the (unchanged) node pointer
returnroot;
}
// Function to find the k-th smallest element in BST
publicstaticintKthSmallest(Node root, intk)
{
// Create an empty stack
Stack<Node> stack = newStack<Node>();
// Loop until the stack is empty or k becomes zero
while(root != null|| stack.Count > 0)
{
// Push all the left subtree nodes onto the stack
while(root != null)
{
stack.Push(root);
root = root.left;
}
// Pop the top node from the stack and check if it is the k-th element
root = stack.Pop();
if(--k == 0)
returnroot.data;
// Set root to the right child and continue with the traversal
root = root.right;
}
// If k is greater than the number of nodes in BST, return -1
return-1;
}
// Driver Code
publicstaticvoidMain()
{
Node root = null;
int[] keys = { 20, 8, 22, 4, 12, 10, 14 };
// Insert all the keys into BST
foreach(intkey inkeys)
root = Insert(root, key);
intk = 4;
// Find the k-th smallest element in BST
intkth_smallest = KthSmallest(root, k);
if(kth_smallest != -1)
Console.WriteLine("K-th smallest element in BST is: "+ kth_smallest);
else
Console.WriteLine("Invalid input");
}
}
Javascript
// Definition of a BST node
class Node {
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
}
}
// Function to insert a new node in BST
functioninsert(root, key) {
// If the tree is empty, return a new node
if(root === null)
returnnewNode(key);
// Otherwise, recur down the tree
if(key < root.data)
root.left = insert(root.left, key);
elseif(key > root.data)
root.right = insert(root.right, key);
// Return the (unchanged) node pointer
returnroot;
}
// Function to find the k-th smallest element in BST
functionkthSmallest(root, k) {
// Create an empty stack
const stack = [];
// Loop until stack is empty or k becomes zero
while(root !== null|| stack.length > 0) {
// Push all the left subtree nodes onto the stack
while(root !== null) {
stack.push(root);
root = root.left;
}
// Pop the top node from the stack and check if it is the k-th element
root = stack.pop();
if(--k === 0)
returnroot.data;
// Set root to the right child and continue with the traversal
root = root.right;
}
// If k is greater than the number of nodes in BST, return -1
return-1;
}
// Driver Code
let root = null;
const keys = [20, 8, 22, 4, 12, 10, 14];
// Insert all the keys into BST
for(const x of keys)
root = insert(root, x);
const k = 4;
// Find the k-th smallest element in BST
const kth_smallest = kthSmallest(root, k);
if(kth_smallest !== -1)
console.log("K-th smallest element in BST is: "+ kth_smallest);
else
console.log("Invalid input");
// This code is contributed by Veerendra_Singh_Rajpoot
Output
K-th smallest element in BST is: 12
Time Complexity: O(h+ k), The time complexity of the Iterative Approach using Stack to find the kth smallest element in a BST is O(h + k), where h is the height of the BST and k is the value of k.
Auxiliary Space: O(h+k), The space complexity of the code is O(h + k), where h is the height of the BST and k is the maximum size of the stack.
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 neveropen!