2

I have an AVL tree while each node consists of:

  • Key
  • Value

The AVL tree is ordered by the keys.

So if I got 2 keys and now I want to find the maximum value between those 2 keys. I've tried adding additional information to each node like the max value in the left subtree and same for the right subtree but I can't get the right algorithm without "losing" some nodes between.

Complexity time: O(log n) worst case.

user550413
  • 4,609
  • 4
  • 25
  • 26

1 Answers1

1

What other operations do you need on this composite tree, and what complexity bounds do you require for them?

If the only restriction is on this look-up-the-max-value-for-a-range-of-keys(j, k) operation, then there is the silly solution of precomputing all these n^2 maxima in arbitrarily much time; you'd store all values for fixed k in an array in node k in the tree; then your operation is reduced to a lookup. However, if you'd want to support insert or delete, the complexity would be something like O(n^2).

A more realistic option would be to store the max of each subtree. There are at most O(log(n)) subtrees between any two nodes, and you encounter all of them on the way from the root to your two keys j and k or just underneath them in the tree, so that would be O(log(n)). This way you'd still have O(log(n)) insertion, but I think deletion would potentially be O(n) now since it's complicated to restore the maximum of a subtree out of which you've removed an entry.

Erik P.
  • 1,577
  • 10
  • 18
  • Of course Insert & Remove in O(log n) as well. – user550413 May 17 '11 at 19:43
  • deletion will also be O(logn): each deletion affects only the ancestors of the deleted vertex. – amit May 17 '11 at 21:08
  • But how will it work? In the way to the 2 keys you encounter many max values that may be values of smaller keys or greater keys and not just max values of the keys between them which interests you. – user550413 May 18 '11 at 08:15
  • 1
    Start at the root. As long as j and k are in the same subtree, just go down that subtree. At some point j will be in the left subtree, k in the right. Now you start maintaining the max m of the values in between that you encounter. Start by setting m = value of that node. (Not the max of the subtree!) Then descend into the left subtree until you find j; every time you go left from a node n, set m = max(m, value(n), max-of-subtree(right-child(n))). Every time you go right, don't update m. For finding k, do the symmetric thing. There's a few easy corner cases needing special rules. – Erik P. May 18 '11 at 13:34