平衡樹——自平衡二叉樹(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?
這裏寫圖片描述
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:
這裏寫圖片描述
L-Rotation:
這裏寫圖片描述
LR-Rotation:
這裏寫圖片描述
RL-Rotation:
這裏寫圖片描述

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.
這裏寫圖片描述

時間複雜度(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.

發佈了37 篇原創文章 · 獲贊 2 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章