Problem 230

Abstract / Summary

Find the kth smallest value in a binary search tree.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
12 lines | 388 bytes | submitted September 1, 2023 | GitHub   20% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

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
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 7.04 | σ = 1.20

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
56 links | 41 authors | 11 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Kth Smallest Element in a BST - Leetcode 230 - Python'
NeetCode 11 mins
Kth Smallest Element in a BST - Leetcode 230 - Python
YouTube video 'kth Smallest Element in a BST | LeetCode 230 | C++, Java, Python | May LeetCoding Day 20'
Knowledge Center 16 mins
kth Smallest Element in a BST | LeetCode 230 | C++, Java, Python | May LeetCoding Day 20
YouTube video 'Leetcode - Kth Smallest Element in a BST (Python)'
Timothy H Chang 5 mins
Leetcode - Kth Smallest Element in a BST (Python)
YouTube video 'Kth Smallest Element in a BST - LeetCode 230 - JavaScript'
AlgoJS 5 mins
Kth Smallest Element in a BST - LeetCode 230 - JavaScript
YouTube video '230. Kth Smallest Element in a BST || leetcode || medium question || c++'
code Explainer 6 mins
230. Kth Smallest Element in a BST || leetcode || medium question || c++
YouTube video 'Daily Leetcode #748: Apr 18, 2022 - 230. Kth Smallest Element in a BST'
Programming Live with Larry 7 mins
Daily Leetcode #748: Apr 18, 2022 - 230. Kth Smallest Element in a BST
YouTube video 'Kth Smallest Element in a BST | Day 20 | [May LeetCoding Challenge] [Leetcode 230] [2020]'
Algorithms Made Easy 3 mins
Kth Smallest Element in a BST | Day 20 | [May LeetCoding Challenge] [Leetcode 230] [2020]
YouTube video 'Kth Smallest Element in a BST | Leetcode 230 | Facebook Amazon Microsoft Adobe | BST'
Naresh Gupta 6 mins
Kth Smallest Element in a BST | Leetcode 230 | Facebook Amazon Microsoft Adobe | BST
YouTube video 'Leetcode 230. Kth Smallest Element in a BST [ JAVASCRIPT ].'
Web Fusion with Bharadwaj 11 mins
Leetcode 230. Kth Smallest Element in a BST [ JAVASCRIPT ].
YouTube video 'Kth Smallest Element in a BST - Leetcode 230 | 3 Inorder Traversal Approaches'
Code With K5KC 12 mins
Kth Smallest Element in a BST - Leetcode 230 | 3 Inorder Traversal Approaches
YouTube video 'Day 243: LeetCode Problem 230. Kth Smallest Element in a BST - Swift'
iOSxBank 9 mins
Day 243: LeetCode Problem 230. Kth Smallest Element in a BST - Swift
YouTube video '31. Leetcode 230. Kth Smallest Element in a BST : JAVA'
Web Fusion with Bharadwaj 16 mins
31. Leetcode 230. Kth Smallest Element in a BST : JAVA
YouTube video 'Leetcode 230 || Kth Smallest Element in a BST || Google || Amazon || Meta || Adobe || Microsoft'
Komal Pal 7 mins
Leetcode 230 || Kth Smallest Element in a BST || Google || Amazon || Meta || Adobe || Microsoft
YouTube video '56. Leetcode 230. Kth Smallest Element in a BST : Javascript'
Web Fusion with Bharadwaj 21 mins
56. Leetcode 230. Kth Smallest Element in a BST : Javascript
YouTube video 'Kth Smallest Element in a BST | Leetcode 230 | Approach + Code with explanation.'
Pirai's Academy 9 mins
Kth Smallest Element in a BST | Leetcode 230 | Approach + Code with explanation.
YouTube video '104. Leetcode 230. Kth Smallest Element in a BST : JAVA'
Web Fusion with Bharadwaj 17 mins
104. Leetcode 230. Kth Smallest Element in a BST : JAVA
YouTube video 'Kth Smallest Element in a BST - LeetCode #230 - C++'
Sean Chuah 13 mins
Kth Smallest Element in a BST - LeetCode #230 - C++
YouTube video 'LeetCode 230 | Kth Smallest Element in a BST | Traverse | Java'
Sleepy Cracker 3 mins
LeetCode 230 | Kth Smallest Element in a BST | Traverse | Java
YouTube video 'LeetCode 230: Kth Smallest Element in a BST | C# Solution | In-order Traversal'
Code Scribbler 7 mins
LeetCode 230: Kth Smallest Element in a BST | C# Solution | In-order Traversal
YouTube video 'Leetcode 230. Kth Smallest Element in a BST - 3 solutions: naive, heap, partial inorder traversal'
Code-Yao 20 mins
Leetcode 230. Kth Smallest Element in a BST - 3 solutions: naive, heap, partial inorder traversal
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

30 solutions   September 1, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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