LeetCode 230: Kth Smallest Element in a BST is a Medium binary search tree problem. This Python walkthrough develops an iterative inorder solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.
This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.
| Difficulty | Medium |
|---|---|
| Topic | Binary Search Tree |
| Reusable pattern | iterative inorder |
| Complexity | O(h+k) typical time and O(h) space |
Recognizing the pattern
BST ordering turns inorder traversal into a sorted stream and lets inherited bounds rule out whole subtrees.
For this problem specifically, push left descendants, pop the next smallest node, decrement k, and then explore its right subtree. The invariant worth writing beside the code is: The next stack pop is the smallest unvisited BST value.
Step-by-step algorithm
- Identify the input state consumed by
kthSmallest(root, k)and initialize the data required by the iterative inorder pattern. - Push left descendants, pop the next smallest node, decrement k, and then explore its right subtree.
- After each update, verify the page’s central invariant: The next stack pop is the smallest unvisited BST value.
- Finish only after the boundary behavior is covered: k is one-based and guaranteed valid.
Python solution
LeetCode supplies the list, tree, or graph node class referenced by this method. The downloadable test suite includes compatible local node definitions so the implementation can also run outside the judge.
class Solution:
def kthSmallest(self, root, k):
stack = []
while True:
while root:
stack.append(root); root = root.left
root = stack.pop(); k -= 1
if k == 0: return root.val
root = root.rightReading the implementation
The main entry point is kthSmallest(root, k). The named working state includes stack, root; those variables make the iterative inorder state visible instead of hiding it in incidental control flow.
The implementation uses 2 loops with separate responsibilities, so preprocessing and the main traversal can each stay linear in their own input. In concrete terms, push left descendants, pop the next smallest node, decrement k, and then explore its right subtree.
Correctness argument
Base case. Empty or terminal subproblems return a result that already satisfies the claim for that smallest state.
Inductive step. Push left descendants, pop the next smallest node, decrement k, and then explore its right subtree. Assuming child or smaller states are correct, the current call combines only results allowed by the problem, so the next stack pop is the smallest unvisited BST value.
Conclusion. Every recursive call reduces the remaining state. The base cases terminate, and induction carries the invariant back to the original input, establishing the returned answer.
Complexity and trade-offs
O(h+k) typical time and O(h) space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.
Collecting all values and sorting works for a general tree, but it ignores the ordering guarantee and uses extra time or space. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.
Regression check
The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.
One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.
bst=tree([4,2,6,1,3]); assert s.Solution530().getMinimumDifference(bst)==1 and Solution().kthSmallest(bst,3)==3Common mistakes and edge cases
- Problem-specific boundary: k is one-based and guaranteed valid.
- Pattern-level pitfall: Use strict bounds when duplicates are invalid and avoid numeric sentinels that conflict with legitimate negative values.
- Invariant check: after every update, confirm that the next stack pop is the smallest unvisited BST value.
Interview review checklist
- Explain why iterative inorder matches the structure of this input.
- State the invariant in one sentence before tracing code: The next stack pop is the smallest unvisited BST value.
- Derive O(h+k) typical time and O(h) space from how many times each element or state is visited.
- Test the boundary explicitly: k is one-based and guaranteed valid.
Browse the searchable 100 LeetCode Python Solutions hub. Previous: 530. Minimum Absolute Difference in BST · Next: 98. Validate Binary Search Tree