Kth Smallest Element in a BST - Problem
Given the root of a binary search tree and an integer k, return the k-th smallest value (1-indexed) of all the values of the nodes in the tree.
A binary search tree (BST) is a tree where for every node, all values in the left subtree are smaller than the node's value, and all values in the right subtree are greater than the node's value.
Follow up: If the BST is modified frequently (insertions and deletions), how would you optimize the solution?
Input & Output
Example 1 — Basic BST
$
Input:
root = [3,1,4,null,2], k = 1
›
Output:
1
💡 Note:
The BST has values [1,2,3,4] in sorted order. The 1st smallest value is 1.
Example 2 — Find 3rd Smallest
$
Input:
root = [5,3,6,2,4,null,null,1], k = 3
›
Output:
3
💡 Note:
The sorted values are [1,2,3,4,5,6]. The 3rd smallest value is 3.
Example 3 — Single Node
$
Input:
root = [1], k = 1
›
Output:
1
💡 Note:
Only one node exists, so the 1st smallest is 1.
Constraints
- The number of nodes in the tree is n.
- 1 ≤ k ≤ n ≤ 104
- 0 ≤ Node.val ≤ 104
Visualization
Tap to expand
Understanding the Visualization
1
Input
BST with nodes [3,1,4,null,2] and k=1
2
Process
In-order traversal gives sorted sequence: 1,2,3,4
3
Output
Return the k-th (1st) smallest element: 1
Key Takeaway
🎯 Key Insight: In-order traversal of BST naturally visits nodes in ascending order
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code