← Back to DSA
#230
Kth Smallest Element in a BST
Kth Smallest Element in a BST solution for LeetCode 230, with the key idea, complexity breakdown, and working code in Java, C++, JavaScript, TypeScript, C, Go, and Rust.
Solve on LeetCode ↗Kth Smallest Element in a BST
Why it belongs on this sheet
This is a practical BST question that rewards understanding in-order traversal order.
Pattern
Inorder gives sorted order
Approach
Traverse the BST in inorder. Each visited node is the next smallest element, so decrement k until it reaches zero.
Java solution
import java.util.ArrayDeque;
import java.util.Deque;
class Solution {
public int kthSmallest(TreeNode root, int k) {
Deque<TreeNode> stack = new ArrayDeque<>();
TreeNode current = root;
while (current != null || !stack.isEmpty()) {
while (current != null) {
stack.push(current);
current = current.left;
}
current = stack.pop();
if (--k == 0) {
return current.val;
}
current = current.right;
}
return -1;
}
}
Complexity
- Time:
O(h + k)on average - Space:
O(h)
Interview note
The iterative solution is a good way to show traversal control without extra arrays.
Dynamic Programming
7 DP Patterns > 100 LeetCode Questions
Most DP questions are repeated ideas. Stop treating DP like chaos. Learn the 7 repeatable patterns that unlock most placement-level questions.
7 patternsProgress tracking
Read 7 patterns (5 min)