Extending the AVL tree to store subtree sizes is usually the best approach here if you need to optimize median queries. It takes O (log n) time, which is pretty fast.
If you will calculate the median a huge number of times, you can use the extended tree and also cache the median value so that you can read it in time O (1). Each time you insert or delete, you may need to recalculate the median in time O (log n), which will slow down the work a little, but will not affect the asymptotic costs.
Another option would be to swap the doubly linked list through nodes in the tree so that you can navigate from node to your successor or predecessor in constant time. If you do, you can save a pointer to the median element, and then insert or delete, move the pointer left or right, if necessary. If you delete the median information, you can simply move the pointer left or right as you would like. This does not require any increase and may be slightly faster, but adds two additional pointers to each node.
Hope this helps!
source share