Given a binary search tree (BST) and an integer k, find k-th smallest element.
Example
Input:
BST:
2
/
1Â Â Â 3
k=3
Output: 3
The 3rd smallest element is 3.
Input Format: There are two arguments in the input. First one is the root of the BST and second one is an integer k.
Output: Return an integer, the k-th smallest element of the BST.
â— 1
â— 1
â— -2 * 10^9
â— You are not allowed to alter the given BST in any way.
We want to find kth smallest element of the given BST. If we can get all the elements of BST in sorted order then our answer will be the kth element. We know that in-order traversal visits elements in the sorted order! But the time complexity of such a solution would be O(N) and auxiliary space used is also O(N).
Note that we don’t need to store all the elements, we can just keep the count of visited nodes; when the counter becomes k it is the node we want!
Your code should look like:
void modified_inorder(root, k)
{
handle base case;
modified_inorder(root->l);
if (answer is not found in left subtree)
{
counter++;
// make sure that you are incrementing
// after the left subtree is visited.
consider current node;
modified_inorder(root->r);
}
}
In terms of the number of tree nodes, it is O(N). Using other variables we can write a tighter bound for this solution. In terms of the height of the tree h and k, it is O(h + k).
The algorithm first traverses down to the leftmost node which takes O(h) time, then traverses k elements in O(k) time. Therefore overall time complexity is O(h + k).
Note that even if k=1 the algorithm has to go all the way down the tree to find the smallest element, visiting all the nodes on the way, and visiting one node takes constant time. So far we have used O(h) time where h is the height of the tree (worst case is when the leftmost leaf of the tree is the longest one).
Having gone all the way down to the smallest element, the algorithm then visits exactly k nodes from there (still constant time per node); complexity so far is O(h) + O(k).
Having found and saved the k-th element value, the algorithm still needs to pop out from the recursion calls so that it can return the answer in the end. For that it will use constant time per level of recursion, per depth of the tree (worst case, again, is when we have found the k-th element in the leaf of the longest branch of the tree). That takes another O(h) time. Therefore the overall time complexity: O(h) + O(k) + O(h) = O(2h + k) = O(h + k).
O(h) due to the stack frames for the recursive calls.
O(N) due to input size.
// -------- START --------
  // kth smallest element is stored in this variable.
  static int kth_element;                      Â
  /*
  when running more than one testcases then dont use static in counter = 0 use this and
  initialize counter = 0 at the beginning of each testcase.  Â
  */
  //int counter = 0;                         Â
  static int counter = 0;
  static void get_k_th_element(TreeNode root, int k)
  {
    // This function uses the idea of inorder_traversal.
    // either root is null or we have already found the answer.      Â
    if (root == null || counter >= k)               Â
    {
      return;
    }
    /*
    first try to find from left subtree, because elements in left suubtree will be smaller
    than the root.
    */
    get_k_th_element(root.left_ptr, k);              Â
    // if we have not found the answer till now.    Â
    if (counter < k)                        Â
    {
      counter++;
      // if current node is the kth node.
      if (counter == k)                     Â
      {
        kth_element = root.val;
        return;
      }
      // we have explored left subtree and the root now explore right subtree.
      get_k_th_element(root.right_ptr, k);            Â
    }
  }
  static int kth_smallest_element(TreeNode root, int k)
  {
    // find kth smallest element
    get_k_th_element(root, k);                   Â
    return kth_element;
  }
  // -------- END --------
The 11 Neural “Power Patterns” For Solving Any FAANG Interview Problem 12.5X Faster Than 99.8% OF Applicants
The 2 “Magic Questions” That Reveal Whether You’re Good Enough To Receive A Lucrative Big Tech Offer
The “Instant Income Multiplier” That 2-3X’s Your Current Tech Salary
The 11 Neural “Power Patterns” For Solving Any FAANG Interview Problem 12.5X Faster Than 99.8% OF Applicants
The 2 “Magic Questions” That Reveal Whether You’re Good Enough To Receive A Lucrative Big Tech Offer
The “Instant Income Multiplier” That 2-3X’s Your Current Tech Salary
Just drop your name and email so we can send your Power Patterns PDF straight to your inbox. No Spam!
By sharing your contact details, you agree to our privacy policy.
Time Zone: Asia/Dhaka
We’ve sent the Power Patterns PDF to your inbox — it should arrive in the next 30 seconds.
📩 Can’t find it? Check your promotions or spam folder — and mark us as safe so you don’t miss future insights.
We’re hosting a private session where FAANG insiders walk through how they actually use these Power Patterns to crack interviews — and what sets top performers apart.
🎯 If you liked the PDF, you’ll love what we’re sharing next.
Time Zone: