1

I've searched a bit and found a related post: Get median from AVL tree? but I'm not too satisfied with the response.

My thoughts on solving this problem:

  • If the balance factor is 0, return root
  • else keep removing the root until the tree is completely balanced, and calculate the median of the roots you just removed

Assuming the AVL tree will keep the balance(by definition?) I've seen some answers suggesting in-order traversal and find median, but I that will require more space and time in my opinion.

Can someone confirm or correct my ideas? thanks!

Community
  • 1
  • 1
Henry
  • 11
  • 1
  • 4

1 Answers1

0

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.

Community
  • 1
  • 1
Ondrej Skopek
  • 778
  • 10
  • 27