#include <bits/stdc++.h>
using namespace std;

// tree node is defined
class TreeNode
{
public:
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int data)
    {
        val = data;
        left = NULL;
        right = NULL;
    }
};

// inorder traversal to find kth minimum element
void kthSmallestRec(TreeNode *root, int K, int &count, int &ans)
{
    if (!root)
        return;
    // reach the 1st minimum node fisrt doing inorder traversal
    kthSmallestRec(root->left, K, count, ans);
    // increment count
    count++;
    if (count == K)
    { // if it's K then the current node value is kth minimum
        ans = root->val;
        return;
    }

    kthSmallestRec(root->right, K, count, ans);
}

// return the Kth minimum element in the given BST rooted at root
int kthSmallest(TreeNode *root, int K)
{
    // Your code here
    int ans = INT_MIN;
    int count = 0;
    kthSmallestRec(root, K, count, ans);

    return ans;
}

int main()
{
    TreeNode *root = new TreeNode(16);
    root->left = new TreeNode(3);
    root->left->right = new TreeNode(13);
    root->left->right->left = new TreeNode(10);
    root->right = new TreeNode(20);
    root->right->left = new TreeNode(18);
    int k = 3;
    cout << "3rd minimum is: " << kthSmallest(root, k) << endl;
    k = 5;
    cout << "5th minimum is: " << kthSmallest(root, k) << endl;
    return 0;
}


Output

3rd minimum is: 13
5th minimum is: 18