Chapter 16: AVL Trees

前言

AVL tree是在每次插入,刪除node時,會注意tree的平衡性。非平衡的BST就是失去BST該有的優異特性,所以不斷保持tree的平衡,就是AVL tree的特色。

大綱

  • Understanding balance

    • Perfect balance

    • "Good-enough" balance

    • Unbalanced

  • Implementation

    • Measuring balance

    • Rotations

      • Left rotation

      • Right rotation

      • Right-left rotation

      • Left-right rotation

    • Balance

    • Revisiting insertion

    • Revisiting remove

Understanding balance

首先,我們要給平衡下個定義,怎樣的狀況才叫做平衡。

  • Perfect balance

    • The definition of a balanced tree is that every level of the tree must be filled, except for the bottom level.

  • "Good-enough" balance

    • The definition of a balanced tree is that every level of the tree must be filled, except for the bottom level

  • Unbalanced

Measuring balance

  • balance factor: 左右子樹的高度差不能超過1。

  • 從樹的底端開始向上找起,找到第一個balance factor大於1或小於-1的node,進行調整。

    • you only need to perform the balancing procedure on the bottom-most node containing the invalid balance factor: the node containing 25

Rotations

當遇到沒有平衡的node, 必須經過rotation,讓這個node恢復平衡,根據不平衡的情況,總共有4種rotation狀況。

  • Left rotation

  • Right rotation

  • Right-left rotation

  • Left-right rotation

Balance

現在已經有上面4種不同rotation方式,接下來就是依據不同情況進行不同的rotaion,讓tree恢復成平衡。

Revisiting insertion

有了balence的function, 接下就是修改insert fucntion,讓每次插入新的node時都要保持tree平衡。

Revisiting remove

跟插入一樣類似的動作

Last updated