How does insert work in an AVL tree, and why is at most one restructuring needed?
Insert the key exactly as in a plain binary search tree, then walk up from the new node updating heights. At the first unbalanced node z, one trinode restructuring brings z's subtree back to the height it had before the insert, so nothing above changes and the walk can stop.
Step by step:
- Search for the key; the search ends at an external node (an empty spot), which becomes the new node. $O(\log n)$.
- Walk up towards the root, recomputing each node's height.
- At the first node whose children differ by 2, restructure (single or double rotation).
Why one is enough: an insert makes the tree at most one level deeper along a single path. The lowest unbalanced node z got exactly one level taller on its heavy side. The restructuring removes that extra level, so z's subtree is now exactly as high as before the insert, and every ancestor sees the same heights it saw before. They were balanced then, so they are balanced now.
That is why the cost breaks down as an $O(\log n)$ search plus $O(1)$ for the repair: the walk up is short, and only one rotation (or one double rotation) happens.
Implementation note: an AVL tree is usually a subclass of the plain search tree: call the inherited insert, then rebalance. Walking back up needs a way to reach the ancestors, either a parent reference in every node or a list of the nodes visited on the way down, which is the path to replay upwards.