Kth Smallest Element in a BST
Question (LC.230)
Given the root of a BST, find the kth smallest element.
Example
I: tree = [3,1,4,null,2], k = 1
3
/ \
1 4
\
2
O: 1
I: tree = [5,3,6,2,4,null,null,1], k = 3
5
/ \
3 6
/ \
2 4
/
1
O: 3 Analysis
Find the ith node in the in order traversal.
Code
The iterator with stack turns out to be slightly faster.
Complexity
Time: O(h + k)
Space: O(h)
Follow Up
What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kth smallest routine?
If we know k is a constant
Maintain a separate data structure. Like a max heap of k element.
Deletion is tricky here but O(k) is not terrible if k is small
insert, delete, find kth smallest
If k is a variable that is part of the query
The current approach is fine O(h) insert + O(h + k) find kth smallest
We can optimize find kth smallest slightly by maintaining a linked list
We need a mapping between TreeNode to ListNode too for insertion
Then O(h) insert, O(h) delete, O(k) find kth smallest
Last updated