This question is an exact duplicate of:
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.
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.
来源:https://stackoverflow.com/questions/6035623/search-max-value-between-2-avl-nodes