Kth Smallest Element in a BST
Last updated
Last updated
Given the root of a BST, find the kth smallest element.
Find the ith node in the in order traversal.
The iterator with stack turns out to be slightly faster.
Time: O(h + k)
Space: O(h)
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
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
insert, delete, find kth smallest