There are two problems in your suggested approach:
- You destroy your tree in the process (or take up twice as much memory for a "backup" copy)
- In the worst case, you need quite a lot of root removals to get a completely balanced tree (I think in the worst-case, it would be close to
2^(n-1)-1
removals)... and you'd still need to calculate the median from that.
The answer in your linked question is right and optimal. The usual way to solve this is to construct a Order statistic tree (by holding the number of elements of the left and right sub-tree for each node). Do note, that you have to compensate the numbers accordingly if a rotation of the AVL tree happens.
See IVlad's answer here. Since an AVL tree guarantees an O(log n)
Search operation and IVlad's algorithm is essentially a Search operation, you can find the k
-th smallest element in O(log n)
time and O(1)
space (not counting the space for the tree itself).
Assuming your tree is indexed from 0 and has n
elements, find the median in the following way:
- if
n
is odd: Find the (n-1)/2
-th element and return it
- if
n
is even: Find the n/2
-th and (n/2)-1
elements and return their average
Also, if changing the tree (left/right element counts) is not an option, see the second part of the answer you linked to.