Kth Smallest Element in a BST - Binary Tree Traversal Pattern

Kth Smallest Element in a BST in Java using the Binary Tree Traversal pattern: problem statement, approach, template, complexity, and interview tips.

Kth Smallest Element in a BST

Problem Statement

Return the kth smallest value in a binary search tree.

Pattern: Binary Tree Traversal

Visit tree nodes in a defined order (inorder, preorder, postorder) using recursion or an explicit stack.

Use this pattern when you must process every node, collect values in a specific order, or build paths from the root.

Approach

  1. Choose the visiting order that matches the question.
  2. Write the recursive form first, then convert to an iterative stack if asked.
  3. Pass accumulated state (path, counter) down or return results up.

Pattern Template (Java)

void inorder(TreeNode node, List<Integer> out) {
    if (node == null) return;
    inorder(node.left, out);
    out.add(node.val);
    inorder(node.right, out);
}

Adapt this template to the exact rules of Kth Smallest Element in a BST: decide what state you track, what condition moves the loop forward, and what the final answer is.

Complexity

O(n) time and O(h) space, where h is the tree height.

Interview Tips

  • Inorder traversal of a BST yields sorted values.
  • Know the iterative version using a stack; it is a common follow-up.
  • Start with a brute-force idea, state its complexity, then explain how the Binary Tree Traversal pattern improves it.
  • Walk through a small example and at least one edge case (empty input, a single element, duplicates).

Continue Learning

Parent: DSA Interview Learning Path | Previous: Binary Tree Paths

Was this guide helpful?

CodeWithVenu is free to read, with no paywall. If this guide saved you time or helped you prepare, a small voluntary contribution helps me write more practical tutorials, architecture guides, and interview-prep content.