Python 0230.py
class Solution:
def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
inorder = []
def deeper(node):
if node and len(inorder) < k: # early exit if k is small
deeper(node.left)
inorder.append(node.val)
deeper(node.right)
deeper(root)
return inorder[k - 1] # zero-based
Difficulty
and has an acceptance rate of about 77% (3+ million submissions).
Typical patterns to solve this problem:
- Binary Search Tree
- Binary Tree
- Depth First Search
- Tree
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a Solution class with a method kthSmallest that returns the k-th smallest value stored in a binary search tree (BST). The algorithm performs an in-order traversal, which naturally visits BST nodes in ascending order, and stops once the desired element has been collected. By limiting the traversal to the first k elements, the method avoids unnecessary work on the remainder of the tree.
Core Logic
The method begins by allocating an empty list named inorder. This list serves as a temporary container for node values encountered during the traversal.
inorder = []
A nested helper function called deeper is defined to carry out the recursive in-order walk. The function receives a single argument node, representing the current subtree root.
def deeper(node):
if node and len(inorder) < k: # early exit if k is small
deeper(node.left)
inorder.append(node.val)
deeper(node.right)
The conditional if node and len(inorder) < k performs two checks: it ensures that the recursion only proceeds when a valid node exists, and it enforces an early termination condition once the list already holds k elements. This guard prevents further descent into subtrees that cannot affect the final answer.
Inside the guard, the left child is visited first (deeper(node.left)), then the current node’s value is appended to inorder, and finally the right child is processed (deeper(node.right)). This ordering respects the in-order sequence: left, root, right.
After defining the helper, the algorithm initiates the traversal from the supplied root.
deeper(root)
When the recursion finishes, the list inorder contains the smallest k values of the BST in sorted order. The method then returns the element at index k-1, which corresponds to the k-th smallest value in a zero-based list.
return inorder[k - 1] # zero-based
Edge Cases Handled
When the input tree is empty (root is None), the guard if node prevents any recursive calls, leaving inorder empty. Attempting to access inorder[k-1] would raise an IndexError, which implicitly signals that the request is invalid for an empty tree.
If k equals 1, the early-exit condition allows the traversal to stop after the very first node value is recorded, avoiding any deeper recursion.
When k exceeds the total number of nodes, the guard len(inorder) < k remains true throughout the entire traversal, causing the algorithm to visit every node. The final access inorder[k-1] will again raise an IndexError, indicating that the requested rank is out of bounds.
The code also gracefully handles trees that are highly unbalanced (e.g., a degenerate linked-list shape). The recursion proceeds along the single branch, and the early-exit condition still limits work to the first k nodes encountered.
Performance Optimizations
The most notable optimization is the early-exit check len(inorder) < k placed at the start of each recursive call. By evaluating the size of the collected list before descending further, the algorithm can abort traversal of subtrees that lie entirely to the right of the k-th smallest element. This reduces the number of recursive invocations and node visits, especially when k is much smaller than the total node count.
Storing values in a plain Python list and appending them as they are discovered provides O(1) amortized insertion, keeping the overhead minimal. The method avoids constructing auxiliary data structures such as stacks or queues, relying solely on the call stack for recursion, which aligns with the natural depth-first nature of in-order traversal.
By returning directly from the list after the traversal, the implementation sidesteps any additional post-processing steps, delivering the result in a single, straightforward lookup.
Overall, the combination of in-order traversal, early termination, and minimal auxiliary storage yields an efficient solution for retrieving the k-th smallest element from a BST.
ELI5 - Simplified Explanation
Imagine you have a big family tree made of numbers. Some numbers are on the left, some are on the right, and some are right in the middle. To find the smallest number, the computer starts at the very top and walks down the left side because the smallest numbers are always hidden deep in the left branches.
The code uses a little helper function that acts like a tiny explorer. This explorer visits every number in a very specific order. It goes all the way to the leftmost spot first, writes down the number it finds, and then checks if there is another number to the right. It keeps doing this until it has collected a list of numbers lined up from smallest to largest. Because this explorer follows a strict path, the list will always have the smallest number at the very beginning and the largest one at the very end. The number you are looking for will be hiding at the spot in the list that matches the number provided.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||||||
| WalkCCC | C++ | Python | Java | |||||||||
| leetcode.ca | C++ | Python | Java | Rust | Go | TS | ||||||
| LeetcodeHelp | C++ | Python | Java | |||||||||
| MemoryLimitExceeded | C++ | Python | ||||||||||
| Progiez | C++ | Python | Java | |||||||||
| github | aylei | Rust | ||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++ | |||||||||||
| bujosa | Python | |||||||||||
| chandansgowda | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| everthis | JS | |||||||||||
| fartem | Ruby | |||||||||||
| FelixFan1122 | C# | |||||||||||
| fengvyi | C++ | |||||||||||
| fpdjsns | C++ | |||||||||||
| gaosq0604 | Python | |||||||||||
| Garvit244 | Python | |||||||||||
| halfrost | Go | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JS | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| lennylxx | C | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| MacJim | C++ | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| sonugiri1043 | C++ | |||||||||||
| suxrobGM | C# | |||||||||||
| trung-hn | Python | |||||||||||
| varunu28 | Java | |||||||||||
| vli02 | C | |||||||||||
| vthwang | Java | |||||||||||
| XiaotaoGuo | C++ | |||||||||||
| yuanliu666 | Kotlin | |||||||||||
| YuriSpiridonov | Python | |||||||||||
| zfang399 | C++ | |||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||
| WalkCCC | C++, Python, Java | |||||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | |||||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||||
| Progiez | C++, Java, Python | |||||||||||
| aylei | Rust | |||||||||||
| begeekmyfriend | C | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++, C++ | |||||||||||
| bujosa | Python | |||||||||||
| chandansgowda | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| chenyanzhe | C++ | |||||||||||
| everthis | JavaScript | |||||||||||
| fartem | Ruby | |||||||||||
| FelixFan1122 | C# | |||||||||||
| fengvyi | C++ | |||||||||||
| fpdjsns | C++ | |||||||||||
| gaosq0604 | Python | |||||||||||
| Garvit244 | Python | |||||||||||
| halfrost | Go | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JavaScript | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| lennylxx | C | |||||||||||
| linouk23 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| MacJim | C++ | |||||||||||
| ruoru | Rust | |||||||||||
| shreymehul | C# | |||||||||||
| sonugiri1043 | C++ | |||||||||||
| suxrobGM | C# | |||||||||||
| trung-hn | Python | |||||||||||
| varunu28 | Java | |||||||||||
| vli02 | C | |||||||||||
| vthwang | Java | |||||||||||
| XiaotaoGuo | C++ | |||||||||||
| yuanliu666 | Kotlin | |||||||||||
| YuriSpiridonov | Python | |||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 94: Binary Tree Inorder Traversal
- problem 671: Second Minimum Node In a Binary Tree
Solved On The Same Day
- problem 144: Binary Tree Preorder Traversal
- problem 145: Binary Tree Postorder Traversal
- problem 222: Count Complete Tree Nodes
- problem 404: Sum of Left Leaves
- problem 501: Find Mode in Binary Search Tree
- problem 543: Diameter of Binary Tree
- problem 559: Maximum Depth of N-ary Tree
- problem 589: N-ary Tree Preorder Traversal
- problem 590: N-ary Tree Postorder Traversal
- problem 637: Average of Levels in Binary Tree
- problem 700: Search in a Binary Search Tree
- problem 703: Kth Largest Element in a Stream
- problem 79: Word Search
- problem 81: Search in Rotated Sorted Array II
- problem 97: Interleaving String
- problem 99: Recover Binary Search Tree
- problem 173: Binary Search Tree Iterator
- problem 199: Binary Tree Right Side View
- problem 235: Lowest Common Ancestor of a Binary Search Tree
- problem 341: Flatten Nested List Iterator
- problem 429: N-ary Tree Level Order Traversal
- problem 508: Most Frequent Subtree Sum
- problem 513: Find Bottom Left Tree Value
- problem 538: Convert BST to Greater Tree
- problem 65: Valid Number
- problem 85: Maximal Rectangle
- problem 87: Scramble String
- problem 126: Word Ladder II
- problem 127: Word Ladder
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality