Open In App

k-th Smallest in BST (Order Statistics in BST)

Last Updated : 03 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a Binary Search Tree (BST) and a positive integer k, find the kth smallest element in the Binary Search Tree. 

Example:

Input: k = 3

th-Largest-element-in-BST

Output: 10
Explanation: The inorder traversal of given BST is [4, 8, 10, 12, 14, 20, 22] and its 3rd smallest element is 10.

[Expected Approach] Using In-Order traversal - O(k) Time and O(h) Space

The idea is to traverse the binary search tree using in-order traversal while maintaining the count of nodes traversed. If the node count becomes equal to k, then return the node.

C++
//Driver Code Starts
// C++ program to find kth 
// smallest value in BST
#include <iostream>
using namespace std;

class Node {
public:
    int data;
    Node* left;
    Node* right;
    Node(int x) {
        data = x;
        left = nullptr; 
        right = nullptr;
    }
};
//Driver Code Ends


// Recursive function for inorder traversal of the tree and 
// find its kth smallest value.
// Returns -1 if value is not found.
int kthSmallestRecur(Node* root, int &cnt, int k) {
    if (root == nullptr) return -1;
    
    // Process left subtree.
    int left = kthSmallestRecur(root->left, cnt, k);
    
    // If kth smallest is found in left 
    // subtree, then return it.
    if (left != -1) return left;
    
    // increment node count
    cnt++;
    
    // If curr node is kth smallest,
    // return it.
    if (cnt == k) return root->data;
    
    // Else process the right subtree
    // and return its value.
    int right = kthSmallestRecur(root->right, cnt, k);
    return right;
}

// Function to find kth smallest value in BST.
int kthSmallest(Node* root, int k) {
    int cnt = 0;
    return kthSmallestRecur(root, cnt, k);
}


//Driver Code Starts
int main() {
    
    // Binary search tree
    //      20
    //    /   \
    //   8     22
    //  / \
    // 4   12
    //    /  \
    //   10   14
    Node* root = new Node(20);
    root->left = new Node(8);
    root->right = new Node(22);
    root->left->left = new Node(4);
    root->left->right = new Node(12);
    root->left->right->left = new Node(10);
    root->left->right->right = new Node(14);
    int k = 3;

    cout << kthSmallest(root, k) << endl;
    return 0;
}
//Driver Code Ends
Java
//Driver Code Starts
// Java program to find kth 
// smallest value in BST

class Node {
    int data;
    Node left, right;

    Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {
//Driver Code Ends


    // Recursive function for inorder traversal of the tree 
	// and find its kth smallest value.
    // Returns -1 if value is not found.
    static int kthSmallestRecur(Node root, int[] cnt, int k) {
        if (root == null) return -1;
        
        // Process left subtree.
        int left = kthSmallestRecur(root.left, cnt, k);
        
        // If kth smallest is found in left 
        // subtree, then return it.
        if (left != -1) return left;
        
        // increment node count
        cnt[0]++;
        
        // If curr node is kth smallest,
        // return it.
        if (cnt[0] == k) return root.data;
        
        // Else process the right subtree
        // and return its value.
        int right = kthSmallestRecur(root.right, cnt, k);
        return right;
    }

    // Function to find kth smallest value in BST.
    static int kthSmallest(Node root, int k) {
        int[] cnt = {0};
        return kthSmallestRecur(root, cnt, k);
    }


//Driver Code Starts
    public static void main(String[] args) {

        // Binary search tree
        //      20
        //    /   \
        //   8     22
        //  / \
        // 4   12
        //    /  \
        //   10   14
        Node root = new Node(20);
        root.left = new Node(8);
        root.right = new Node(22);
        root.left.left = new Node(4);
        root.left.right = new Node(12);
        root.left.right.left = new Node(10);
        root.left.right.right = new Node(14);
        int k = 3;

        System.out.println(kthSmallest(root, k));
    }
}

//Driver Code Ends
Python
#Driver Code Starts
# Python program to find kth 
# smallest value in BST

class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None
#Driver Code Ends


# Recursive function for inorder traversal of the tree 
# and find its kth smallest value.
# Returns -1 if value is not found.
def kthSmallestRecur(root, cnt, k):
    if root is None:
        return -1
    
    # Process left subtree.
    left = kthSmallestRecur(root.left, cnt, k)
    
    # If kth smallest is found in left 
    # subtree, then return it.
    if left != -1:
        return left
    
    # increment node count
    cnt[0] += 1
    
    # If curr node is kth smallest,
    # return it.
    if cnt[0] == k:
        return root.data
    
    # Else process the right subtree
    # and return its value.
    right = kthSmallestRecur(root.right, cnt, k)
    return right

# Function to find kth smallest value in BST.
def kthSmallest(root, k):
    cnt = [0]
    return kthSmallestRecur(root, cnt, k)


#Driver Code Starts
if __name__ == "__main__":
    
    # Binary search tree
    #      20
    #    /   \
    #   8     22
    #  / \
    # 4   12
    #    /  \
    #   10   14
    root = Node(20)
    root.left = Node(8)
    root.right = Node(22)
    root.left.left = Node(4)
    root.left.right = Node(12)
    root.left.right.left = Node(10)
    root.left.right.right = Node(14)
    k = 3

    print(kthSmallest(root, k))

#Driver Code Ends
C#
//Driver Code Starts
// C# program to find kth 
// smallest value in BST

using System;

class Node {
    public int data;
    public Node left, right;

    public Node(int x) {
        data = x;
        left = null;
        right = null;
    }
}

class GfG {
//Driver Code Ends


    // Recursive function for inorder traversal of the tree 
	// and find its kth smallest value.
    // Returns -1 if value is not found.
    static int kthSmallestRecur(Node root, ref int cnt, int k) {
        if (root == null) return -1;
        
        // Process left subtree.
        int left = kthSmallestRecur(root.left, ref cnt, k);
        
        // If kth smallest is found in left 
        // subtree, then return it.
        if (left != -1) return left;
        
        // increment node count
        cnt++;
        
        // If curr node is kth smallest,
        // return it.
        if (cnt == k) return root.data;
        
        // Else process the right subtree
        // and return its value.
        int right = kthSmallestRecur(root.right, ref cnt, k);
        return right;
    }

    // Function to find kth smallest value in BST.
    static int kthSmallest(Node root, int k) {
        int cnt = 0;
        return kthSmallestRecur(root, ref cnt, k);
    }


//Driver Code Starts
    static void Main(string[] args) {

        // Binary search tree
        //      20
        //    /   \
        //   8     22
        //  / \
        // 4   12
        //    /  \
        //   10   14
        Node root = new Node(20);
        root.left = new Node(8);
        root.right = new Node(22);
        root.left.left = new Node(4);
        root.left.right = new Node(12);
        root.left.right.left = new Node(10);
        root.left.right.right = new Node(14);
        int k = 3;

        Console.WriteLine(kthSmallest(root, k));
    }
}

//Driver Code Ends
JavaScript
//Driver Code Starts
// JavaScript program to find kth 
// smallest value in BST

class Node {
    constructor(x) {
        this.data = x;
        this.left = null;
        this.right = null;
    }
}
//Driver Code Ends


// Recursive function for inorder traversal of the tree 
// and find its kth smallest value.
// Returns -1 if value is not found.
function kthSmallestRecur(root, cnt, k) {
    if (root === null) return -1;
    
    // Process left subtree.
    let left = kthSmallestRecur(root.left, cnt, k);
    
    // If kth smallest is found in left 
    // subtree, then return it.
    if (left !== -1) return left;
    
    // increment node count
    cnt[0]++;
    
    // If curr node is kth smallest,
    // return it.
    if (cnt[0] === k) return root.data;
    
    // Else process the right subtree
    // and return its value.
    let right = kthSmallestRecur(root.right, cnt, k);
    return right;
}

// Function to find kth smallest value in BST.
function kthSmallest(root, k) {
    let cnt = [0];
    return kthSmallestRecur(root, cnt, k);
}


//Driver Code Starts
// Driver Code
// Binary search tree
//      20
//    /   \
//   8     22
//  / \
// 4   12
//    /  \
//   10   14
const root = new Node(20);
root.left = new Node(8);
root.right = new Node(22);
root.left.left = new Node(4);
root.left.right = new Node(12);
root.left.right.left = new Node(10);
root.left.right.right = new Node(14);
const k = 3;

console.log(kthSmallest(root, k));

//Driver Code Ends

Output
10

We can optimize the space using Morris Traversal. Refer K’th smallest element in BST using O(1) Extra Space for details.

[Alternate Approach] Using Augmented Tree - O(h) Time and O(h) Space

The idea is to include a new data member ''lCount for each node. We can keep track of elements in the left subtree of every node while building the tree and storing it in this new data member.
Assuming that the root is having 'lCount' nodes in its left subtree. If k is equal to lCount + 1, then root is k-th node. If k is less than lCount + 1, we will continue our search (recursion) for the kth smallest element in the left subtree of root. If k is greater than lCount + 1, we continue our search in the right subtree. Note that we need the count of elements in the left subtree only.

C++
//Driver Code Starts
// C++ program to find kth 
// smallest value in BST
#include <iostream>
using namespace std;

class Node {
public:
    int data;
    int lCount;
    Node* left;
    Node* right;
    Node(int x, int l) {
        data = x;
        lCount = l;
        left = nullptr; 
        right = nullptr;
    }
};
//Driver Code Ends


// Recursive function for inorder traversal of the tree  
// and find its kth smallest value.
// Returns -1 if value is not found.
int kthSmallestRecur(Node* root, int &k) {
    if (root == nullptr) return -1;

    // Search left subtree
    if (k < root->lCount+1) {
        return kthSmallestRecur(root->left, k);
    }
    
    // return curr node 
    else if (k == root->lCount+1) {
        return root->data;
    }
    
    // decrement k by (lCount+1) and 
    // search right subtree
    else {
        k = k - (root->lCount+1);
        return kthSmallestRecur(root->right, k);
    }
}

// Function to find kth smallest value in BST.
int kthSmallest(Node* root, int k) {
    return kthSmallestRecur(root, k);
}


//Driver Code Starts
int main() {
    
    // Binary search tree
    //      20
    //    /   \
    //   8     22
    //  / \
    // 4   12
    //    /  \
    //   10   14
    Node* root = new Node(20, 5);
    root->left = new Node(8, 1);
    root->right = new Node(22, 0);
    root->left->left = new Node(4, 0);
    root->left->right = new Node(12, 1);
    root->left->right->left = new Node(10, 0);
    root->left->right->right = new Node(14, 0);
    int k = 3;

    cout << kthSmallest(root, k) << endl;
    return 0;
}
//Driver Code Ends
Java
//Driver Code Starts
// Java program to find kth 
// smallest value in BST

class Node {
    int data;
    int lCount;
    Node left, right;

    Node(int x, int l) {
        data = x;
        lCount = l;
        left = null;
        right = null;
    }
}

class GfG {
//Driver Code Ends


    // Recursive function for inorder traversal of the tree  
    // and find its kth smallest value.
    // Returns -1 if value is not found.
    static int kthSmallestRecur(Node root, int[] k) {
        if (root == null) return -1;

        // Search left subtree
        if (k[0] < root.lCount + 1) {
            return kthSmallestRecur(root.left, k);
        }
        
        // return curr node 
        else if (k[0] == root.lCount + 1) {
            return root.data;
        }
        
        // decrement k by (lCount+1) and 
        // search right subtree
        else {
            k[0] = k[0] - (root.lCount + 1);
            return kthSmallestRecur(root.right, k);
        }
    }

    // Function to find kth smallest value in BST.
    static int kthSmallest(Node root, int k) {
        int[] kRef = {k};
        return kthSmallestRecur(root, kRef);
    }


//Driver Code Starts
    public static void main(String[] args) {

        // Binary search tree
        //      20
        //    /   \
        //   8     22
        //  / \
        // 4   12
        //    /  \
        //   10   14
        Node root = new Node(20, 5);
        root.left = new Node(8, 1);
        root.right = new Node(22, 0);
        root.left.left = new Node(4, 0);
        root.left.right = new Node(12, 1);
        root.left.right.left = new Node(10, 0);
        root.left.right.right = new Node(14, 0);
        int k = 3;

        System.out.println(kthSmallest(root, k));
    }
}

//Driver Code Ends
Python
#Driver Code Starts
# Python program to find kth 
# smallest value in BST

class Node:
    def __init__(self, x, l):
        self.data = x
        self.lCount = l
        self.left = None
        self.right = None
#Driver Code Ends


# Recursive function for inorder traversal of the tree  
# and find its kth smallest value.
# Returns -1 if value is not found.
def kthSmallestRecur(root, k):
    if root is None:
        return -1

    # Search left subtree
    if k[0] < root.lCount + 1:
        return kthSmallestRecur(root.left, k)
    
    # return curr node 
    elif k[0] == root.lCount + 1:
        return root.data
    
    # decrement k by (lCount+1) and 
    # search right subtree
    else:
        k[0] -= (root.lCount + 1)
        return kthSmallestRecur(root.right, k)

# Function to find kth smallest value in BST.
def kthSmallest(root, k):
    kRef = [k]
    return kthSmallestRecur(root, kRef)


#Driver Code Starts
if __name__ == "__main__":
    
    # Binary search tree
    #      20
    #    /   \
    #   8     22
    #  / \
    # 4   12
    #    /  \
    #   10   14
    root = Node(20, 5)
    root.left = Node(8, 1)
    root.right = Node(22, 0)
    root.left.left = Node(4, 0)
    root.left.right = Node(12, 1)
    root.left.right.left = Node(10, 0)
    root.left.right.right = Node(14, 0)
    k = 3

    print(kthSmallest(root, k))

#Driver Code Ends
C#
//Driver Code Starts
// C# program to find kth 
// smallest value in BST

using System;

class Node {
    public int data;
    public int lCount;
    public Node left, right;

    public Node(int x, int l) {
        data = x;
        lCount = l;
        left = null;
        right = null;
    }
}

class GfG {
//Driver Code Ends


    // Recursive function for inorder traversal of the tree  
    // and find its kth smallest value.
    // Returns -1 if value is not found.
    static int kthSmallestRecur(Node root, ref int k) {
        if (root == null) return -1;

        // Search left subtree
        if (k < root.lCount + 1) {
            return kthSmallestRecur(root.left, ref k);
        }
        
        // return curr node 
        else if (k == root.lCount + 1) {
            return root.data;
        }
        
        // decrement k by (lCount+1) and 
        // search right subtree
        else {
            k -= (root.lCount + 1);
            return kthSmallestRecur(root.right, ref k);
        }
    }

    // Function to find kth smallest value in BST.
    static int kthSmallest(Node root, int k) {
        return kthSmallestRecur(root, ref k);
    }


//Driver Code Starts
    static void Main(string[] args) {

        // Binary search tree
        //      20
        //    /   \
        //   8     22
        //  / \
        // 4   12
        //    /  \
        //   10   14
        Node root = new Node(20, 5);
        root.left = new Node(8, 1);
        root.right = new Node(22, 0);
        root.left.left = new Node(4, 0);
        root.left.right = new Node(12, 1);
        root.left.right.left = new Node(10, 0);
        root.left.right.right = new Node(14, 0);
        int k = 3;

        Console.WriteLine(kthSmallest(root, k));
    }
}

//Driver Code Ends
JavaScript
//Driver Code Starts
// JavaScript program to find kth 
// smallest value in BST

class Node {
    constructor(x, l) {
        this.data = x;
        this.lCount = l;
        this.left = null;
        this.right = null;
    }
}
//Driver Code Ends


// Recursive function for inorder traversal of the tree  
// and find its kth smallest value.
// Returns -1 if value is not found.
function kthSmallestRecur(root, k) {
    if (root === null) return -1;

    // Search left subtree
    if (k[0] < root.lCount + 1) {
        return kthSmallestRecur(root.left, k);
    }
    
    // return curr node 
    else if (k[0] === root.lCount + 1) {
        return root.data;
    }
    
    // decrement k by (lCount+1) and 
    // search right subtree
    else {
        k[0] -= (root.lCount + 1);
        return kthSmallestRecur(root.right, k);
    }
}

// Function to find kth smallest value in BST.
function kthSmallest(root, k) {
    let kRef = [k];
    return kthSmallestRecur(root, kRef);
}


//Driver Code Starts
// Driver Code
// Binary search tree
//      20
//    /   \
//   8     22
//  / \
// 4   12
//    /  \
//   10   14
const root = new Node(20, 5);
root.left = new Node(8, 1);
root.right = new Node(22, 0);
root.left.left = new Node(4, 0);
root.left.right = new Node(12, 1);
root.left.right.left = new Node(10, 0);
root.left.right.right = new Node(14, 0);
const k = 3;

console.log(kthSmallest(root, k));

//Driver Code Ends

Output
10

Next Article

Similar Reads