If I am given a certain set of numbers (which I store in a balanced binary search tree for easiness), then I want to answer a query that requires me to inform what is the ith smallest number between [A,B], what would be a fast algorithm to perform that task?
Technically I could traverse the tree from the root searching for A (or a number immediately greater than that if A not present), than backtrack searching for B (or a number smaller than B), and while doing that I could keep a counter for i, to determine when I would be at the ith number. But that does not seem optimal to me.
Can I perform this operation on O(log n), height of the tree that I’m using to store the universal set of numbers?
Thank you
You certainly can do that, if you can keep some information in nodes. To make traversal
O(logn), we need for each node to know, how many nodes its right subtree has. (You can maintain this information and still have adding to/removing from tree in O(log(n)) time)The code should be quite self-explanatory.
We start from
currentNodebeing the first node with number>= Aand look for k-th element (k is 0-based).kissmall.
Nodestruct with pointers to left and right subtrees). So, although algorithm is simple, implementing it might be difficult.Bfrom your question.