Kth Smallest element in a BST


Link: LeetCode - Kth Smallest Element in a BST


Problem Statement

Given the root of a binary search tree and an integer k, return the kth smallest element in the BST.


Examples

Example 1:

Input: root = [3,1,4,null,2], k = 1
Output: 1

Example 2:

Input: root = [5,3,6,2,4,null,null,1], k = 3
Output: 3

Constraints


Intuition

In a Binary Search Tree, an inorder traversal yields the elements in sorted order.

So, the kth smallest element is the kth node visited during an inorder traversal.


Approach: Inorder Traversal (Recursive)


Java Code

class Solution {
    private int count = 0;
    private int result = -1;

    public int kthSmallest(TreeNode root, int k) {
        inorder(root, k);
        return result;
    }

    private void inorder(TreeNode node, int k) {
        if (node == null) return;

        inorder(node.left, k);

        count++;
        if (count == k) {
            result = node.val;
            return;
        }

        inorder(node.right, k);
    }
}

Alternate Approach: Iterative Inorder with Stack

class Solution {
    public int kthSmallest(TreeNode root, int k) {
        Stack<TreeNode> stack = new Stack<>();

        while (true) {
            while (root != null) {
                stack.push(root);
                root = root.left;
            }

            root = stack.pop();
            k--;

            if (k == 0) return root.val;

            root = root.right;
        }
    }
}

Time & Space Complexity


Dry Run

Tree:

     5
    / \
   3   6
  / \
 2   4
/
1

k = 3

Inorder traversal: 1 → 2 → 3 → 4 → 5 → 6


Conclusion

This problem demonstrates how the inorder traversal of a BST can directly help in selecting order-based queries like finding the kth smallest or kth largest elements.