Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep minimum and maximum take O(1) time in a balanced binary search tree, without mucking about with pointers?

The excise 3-7 in "Algorithm Design Manual" book says:

Suppose you have access to a balanced dictionary data structure, which supports each of the operations search, insert, delete, minimum, maximum, successor, and predecessor in O(log n) time. Explain how to modify the insert and delete operations so they still take O(log n) but now minimum and maximum take O(1) time. (Hint: think in terms of using the abstract dictionary operations, instead of mucking about with pointers and the like.)

Without the hints, I think this question is fairly easy.

Here is my solution:

for the tree, I just maintain a pointer min always pointing to minimum, and another pointer max always pointing to maximum.

When inserting x, I just compare min.key with x.key, if min.key > x.key, then min = x; and also do this for max, if necessary.

When deleting x, if min==x, then min = successor(x); if max==x, then max = predecessor(x);

But the hint says I can't mucking about the pointers and the like. Does my solution muck about with pointers?

If we can't use extra points, how can I get O(1) for minimum and maximum?

Thanks

like image 262
Jackson Tale Avatar asked Mar 07 '12 13:03

Jackson Tale


People also ask

How do you find the minimum and maximum of a binary search tree?

In Binary Search Tree, we can find maximum by traversing right pointers until we reach the rightmost node. But in Binary Tree, we must visit every node to figure out maximum. So the idea is to traverse the given tree and for every node return maximum of 3 values. Node's data.

How do you keep a binary search tree balanced?

Given the root of a binary search tree, return a balanced binary search tree with the same node values. If there is more than one answer, return any of them. A binary search tree is balanced if the depth of the two subtrees of every node never differs by more than 1 .

What is the big O complexity for searching in a balanced binary search tree?

In any binary search tree the time complexity taken is O(h), where h is the height of the tree.. Since it is given that tree is balanced binary search tree so searching for an element in worst case is O(logn).


1 Answers

Your answer is the same one I would give - you're not messing with pointers, you're just storing the min/max values.

So, just be more confident :)

like image 183
BlueRaja - Danny Pflughoeft Avatar answered Nov 15 '22 00:11

BlueRaja - Danny Pflughoeft