🧠 Approach: Inorder Traversal (Because BST is Sorted Inorder)
In a BST, an inorder traversal returns nodes in ascending order.
So we:
- Do an inorder traversal.
- Keep a counter as we visit nodes.
- When the counter hits k, we’ve found the kth smallest element.
We short-circuit the recursion as soon as we find the result for efficiency.
✅ Code (JavaScript):
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val === undefined ? 0 : val);
 *     this.left = (left === undefined ? null : left);
 *     this.right = (right === undefined ? null : right);
 * }
 */
/**
 * @param {TreeNode} root
 * @param {number} k
 * @return {number}
 */
var kthSmallest = function (root, k) {
  let count = 0;
  let result = null;
  function inorder(node) {
    if (!node || result !== null) return;
    inorder(node.left);
    count++;
    if (count === k) {
      result = node.val;
      return;
    }
    inorder(node.right);
  }
  inorder(root);
  return result;
};
🧪 Example:
For this BST:
     5
    / \
   3   6
  / \
 2   4
/
1
Inorder traversal: [1, 2, 3, 4, 5, 6]
- 
k = 3→ result =3
⏱ Time & Space Complexity
| Type | Complexity | 
|---|---|
| Time | O(h + k) in the best case (early exit), O(n) worst case | 
| Space | O(h) for recursion stack (h = height of tree) | 
In a balanced BST, h = log n. In worst case (like a skewed tree), h = n.
 

 
    
Top comments (0)