data-structurestime-complexityavl-tree

Undo insertion in AVL tree: best possible time complexity?


I did a test on AVL trees. One question introduced an undo function that can only be called after an insertion into the AVL tree, and which removes the previously inserted node. I'm allowed to change the way I insert a value as long as it still has O(log n) time complexity.

The question then was: what is the best time complexity for this undo function, and why?

I thought it was O(log n) because normal deletion could require rotations for every node in the path from the root to the node inserted. But apparently this is not the correct answer. What am I missing?


Solution

  • The undo action can be done in O(1) time, but indeed you'll have to change the way you insert a node.

    We know a few things about the last inserted node in a standard AVL tree:

    Although the first two points hint at a O(1) undo operation, the last point means we still have a O(logš¯‘›) worst case.

    Because of that last "obstacle", I would suggest the following approach:

    Concluding: with this type of "postponed rebalanincg", you can implement an undo with O(1) time complexity.