# Find k-th smallest element in BST (Order Statistics in BST) in C++

Suppose we have a binary search tree and a value K as input, we have to find K-th smallest element in the tree.

So, if the input is like k = 3, then the output will be 15.

To solve this, we will follow these steps −

• Define a function find_kth_smallest(), this will take root, count, k,

• if root is NULL, then −

• return NULL

• left = find_kth_smallest(left of root, count, k)

• if left is not NULL, then −

• return left

• (increase count by 1)

• if count is same as k, then −

• return root

• return find_kth_smallest(right of root, count, k)

• From the main method, do the following −

• count := 0

• res = find_kth_smallest(root, count, k)

• if res is NULL, then −

• Otherwise

• display val of res

## Example (C++)

Let us see the following implementation to get better understanding −

Live Demo

#include <iostream>
using namespace std;
struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode(int x) {
val = x;
left = right = NULL;
}
};
TreeNode* find_kth_smallest(TreeNode* root, int &count, int k) {
if (root == NULL)
return NULL;
TreeNode* left = find_kth_smallest(root->left, count, k);
if (left != NULL)
return left;
count++;
if (count == k)
return root;
return find_kth_smallest(root->right, count, k);
}
void kth_smallest(TreeNode* root, int k) {
int count = 0;
TreeNode* res = find_kth_smallest(root, count, k);
if (res == NULL)
else
cout << res->val;
}
int main() {
TreeNode* root = new TreeNode(25);
root->left = new TreeNode(13);
root->right = new TreeNode(27);
root->left->left = new TreeNode(9);
root->left->right = new TreeNode(17);
root->left->right->left = new TreeNode(15);
root->left->right->right = new TreeNode(19);
int k = 3;
kth_smallest(root, k);
}

## Input

TreeNode* root = new TreeNode(25); root->left = new TreeNode(13);
root->right = new TreeNode(27); root->left->left = new
TreeNode(9); root->left->right = new TreeNode(17); root- >left->right->left = new TreeNode(15); root->left->right->right = new TreeNode(19); k = 3

## Output

15

Updated on: 25-Aug-2020

378 Views 