平衡树——自平衡二叉树(Balanced Tree - AVL Tree)

平衡树——自平衡二叉树(Balanced Tree - AVL Tree)


定义(Definition)
An AVL tree is a self-balancing binary search tree. It was named after its two inventors: Georgy Adelson-Velsky and Evgenii Landis.

Recall that we define the height of the empty tree as -1. For a binary search tree, let the balance factor to be the difference between the height of its left sub-tree and that of its right sub-tree. For each sub-tree in AVL tree, the balance factor of each node is -1, 0 or 1.

Which are AVL trees?
平衡树——自平衡二叉树(Balanced Tree - AVL Tree)_第1张图片
The first one and second one are AVL trees.
The third one is not AVL tree because the height of node 10 is 2.
the fourth one is also not AVL tree because the height of node 20 is -2.

构造自平衡二叉树(Building an AVL Tree)
We can build an AVL tree by inserting node to an empty tree one by one. If insertion of new node makes the tree unbalanced(which is balance factor is not -1, 0 or 1), transform the tree to regain its balance by using some rotations.
R-Rotation:
平衡树——自平衡二叉树(Balanced Tree - AVL Tree)_第2张图片
L-Rotation:
平衡树——自平衡二叉树(Balanced Tree - AVL Tree)_第3张图片
LR-Rotation:
平衡树——自平衡二叉树(Balanced Tree - AVL Tree)_第4张图片
RL-Rotation:
平衡树——自平衡二叉树(Balanced Tree - AVL Tree)_第5张图片

Along an unbalanced path, we might have several unbalanced nodes. Where do we start? Generally, we start from the lowest unbalanced subtree.

示例(Example)
A, L, G, O, R, I, T, H, M.
平衡树——自平衡二叉树(Balanced Tree - AVL Tree)_第6张图片

时间复杂度(Time Complexity)
Both insertion and deletion are Θ(log n).
For random data, the height of of AVL tree is log2n.

写在最后的话(PS)
There are two more balanced binary search trees: red-black tree and splay tree.
Welcome questions always and forever.

你可能感兴趣的:(算法)