LeetCode 230 · BST
Kth Smallest Element in a BST
LeetCode 230 · Medium · solution, intuition & step-by-step walkthrough
In-order traversal → index k−1.
MediumTreeDepth-First SearchBinary Search TreeBinary Tree
0 msruntime · beats 100%
54.5 MBmemory · beats 100%
1approach
4accepted runs · last 15 Dec 2024
This is how I solved Kth Smallest Element in a BST (LeetCode 230), a medium problem from the BST pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
An in-order traversal of a BST lists values in sorted order, so the kth value visited is the kth smallest.
Approach
- 1
In-order DFS into a list.
- 2
Return arr[k − 1].
How I solved it
In-order listPythonO(n) time · O(n) space
class Solution:
def kthSmallest(self, root, k):
arr = []
def dfs(node):
if node is None:
return
dfs(node.left)
arr.append(node.val)
dfs(node.right)
dfs(root)
return arr[k - 1]Loading the step-through…
Kth Smallest Element in a BST — FAQ
What is the intuition behind Kth Smallest Element in a BST?
An in-order traversal of a BST lists values in sorted order, so the kth value visited is the kth smallest.
How do you solve Kth Smallest Element in a BST (LeetCode 230)?
1. In-order DFS into a list. 2. Return arr[k − 1].
What is the time and space complexity of Kth Smallest Element in a BST?
Time: O(n). Space: O(n). (Accepted approach: In-order list.)
What are common mistakes in Kth Smallest Element in a BST?
Stopping the traversal after k nodes makes it O(h + k).