Description

Kth Smallest Element in a BST

Given the root of a binary search tree, and an integer k, return the kth smallest value (1-indexed) of all the values of the nodes in the tree.

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:

  • The number of nodes in the tree is n.
  • 1 <= k <= n <= 104
  • 0 <= Node.val <= 104

Follow up: If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?

Approach - Iterative

  • Keep pushing left elements then start popping and then push starting from right
  • Time: O(n) Space: O(n)
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int kthSmallest(TreeNode root, int k) {
        TreeNode c = root;
        Stack<TreeNode> s = new Stack<>();
        // In-order traversal using stack
        while (!s.isEmpty() || c != null) {
            // Go to the leftmost node
            while (c != null) {
                s.push(c);
                c = c.left;
            }
            // Pop the node from the stack and process it
            c = s.pop();
            k--;
            if (k == 0) return c.val;
            // Move to the right subtree
            c = c.right;
        }
        return -1;
    }
}

Primary Approach: Iterative Inorder Traversal ( Time, Space)

Intuition

An inorder traversal () of a Binary Search Tree visits nodes in strictly ascending order:

  1. Use an explicit stack to traverse left until reaching a null node.
  2. Pop the top node from the stack (this is the next smallest element).
  3. Decrement . When , the current node value is the -th smallest element.
  4. Move to curr = curr.right and repeat.
  5. Why Iterative? Stopping early as soon as reaches avoids visiting the remaining nodes in the tree.
import java.util.ArrayDeque;
import java.util.Deque;
 
class Solution {
    public int kthSmallest(TreeNode root, int k) {
        Deque<TreeNode> stack = new ArrayDeque<>();
        TreeNode curr = root;
 
        while (curr != null || !stack.isEmpty()) {
            // Push all left children to reach the smallest unvisited element
            while (curr != null) {
                stack.push(curr);
                curr = curr.left;
            }
 
            curr = stack.pop();
            k--;
 
            // Target reached
            if (k == 0) {
                return curr.val;
            }
 
            // Move to right subtree
            curr = curr.right;
        }
 
        return -1;
    }
}
 

Complexity

  • Time Complexity: — Traverses down to tree height , then processes nodes before returning ( for balanced trees).
  • Space Complexity: — Stack holds at most nodes at any point ( for balanced, for skewed).

Alternative Approach: Recursive Inorder DFS ( Time, Space)

Intuition

The same ascending-order logic implemented recursively with a class-level counter:

  1. Traverses the left subtree recursively.
  2. Increments count. If count == k, saves result = node.val and returns early.
  3. Traverses the right subtree if -th element hasn’t been found yet.
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 || count >= k) return;
 
        inorder(node.left, k);
 
        count++;
        if (count == k) {
            result = node.val;
            return;
        }
 
        inorder(node.right, k);
    }
}
 

Complexity

  • Time Complexity: — Stops recursive calls as soon as count == k.
  • Space Complexity: — Stack space bounded by tree height .

Key Interview Discussion Points

  • Follow-Up (Frequent Insertions/Deletions): If the BST changes frequently and -th smallest queries are called often, standard traversal is too slow.
  • Optimization: Augment each tree node to store leftCount (the number of nodes in its left subtree) or size (total nodes in its subtree).
  • Query Execution:
    • If , return current node.val.
    • If , search left subtree.
    • If , search right subtree for -th element.
  • Reduces query time to (or if maintained as a Red-Black / AVL Tree).

Easy Memory Rule

“Inorder Traversal gives sorted order Decrement on node visit Return node value when !”