互動實驗室在瀏覽器中執行

AVL 平衡樹實驗室

自平衡二元樹自平衡模擬,動態展示 LL、RR、LR、RL 四種旋轉。

速度:
平衡的 AVL 樹。節點旁的數字是平衡因子(左子樹高度 − 右子樹高度)。
旋轉情形:
100200300500600700800
節點數: 7高度: 3 失衡(|bf| > 1)
虛擬碼
1insert(node, v):
2 BST-insert v below node
3 node.height = 1 + max(h(left), h(right))
4 bf = h(left) - h(right)
5 if bf > 1 and v < left.key: rotateRight (LL)
6 if bf < -1 and v > right.key: rotateLeft (RR)
7 if bf > 1: rotateLeft(left); rotateRight (LR)
8 if bf < -1: rotateRight(right); rotateLeft (RL)

關於本工具

AVL 樹是一種會自我平衡的二叉搜尋樹。每個節點記錄自己的高度,平衡因子(左子樹高度減右子樹高度)必須保持在 −1 到 +1 之間。插入或刪除讓某個節點超出這個範圍時,通過一次或兩次旋轉恢復平衡,因此樹高始終不超過約 1.44·log₂ n。

本實驗室顯示每個節點的平衡因子,在回溯時高亮第一個失衡節點,並標明正在執行的旋轉型別(LL、RR、LR 或 RL),讓你清楚地看到樹為什麼會變形。

使用方法 AVL 平衡樹實驗室

  1. 逐個插入鍵,或使用“插入有序序列”預設——這正是讓普通 BST 退化的輸入。
  2. 觀察每次插入後平衡因子的變化。紅色的 ±2 表示該節點需要旋轉。
  3. 跟隨旋轉步驟:狀態列會寫明旋轉型別和涉及的節點。
  4. 也試試刪除:與插入不同,刪除可能在通往根的多個層級上觸發旋轉。

範例

RR 型

輸入
依次插入 10、20、30
結果
節點 10 的平衡因子變為 −2 → 一次左旋 → 20 成為根,孩子是 10 和 30

LR 型

輸入
依次插入 30、10、20
結果
先在 10 處左旋,再在 30 處右旋 → 根為 20

有序輸入依然很矮

輸入
按順序插入 1 … 15
結果
得到高度為 4 的滿二叉樹,而不是 15 個節點的鏈

五種語言的程式碼實作

同一演算法的 Python、JavaScript、Java、Go 和 C++ 實作。每段程式都完整可執行,註解中標出了它的輸出結果。

class Node:
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None
        self.height = 1


def height(n):
    return n.height if n else 0


def update(n):
    n.height = 1 + max(height(n.left), height(n.right))


def balance(n):
    return height(n.left) - height(n.right)


def rotate_right(y):
    x = y.left
    y.left = x.right
    x.right = y
    update(y)
    update(x)
    return x


def rotate_left(x):
    y = x.right
    x.right = y.left
    y.left = x
    update(x)
    update(y)
    return y


def insert(node, key):
    if node is None:
        return Node(key)
    if key < node.key:
        node.left = insert(node.left, key)
    elif key > node.key:
        node.right = insert(node.right, key)
    else:
        return node
    update(node)
    b = balance(node)
    if b > 1 and key < node.left.key:      # LL
        return rotate_right(node)
    if b < -1 and key > node.right.key:    # RR
        return rotate_left(node)
    if b > 1:                              # LR
        node.left = rotate_left(node.left)
        return rotate_right(node)
    if b < -1:                             # RL
        node.right = rotate_right(node.right)
        return rotate_left(node)
    return node


def preorder(n, out):
    if n:
        out.append(n.key)
        preorder(n.left, out)
        preorder(n.right, out)
    return out


root = None
for k in [10, 20, 30, 40, 50, 25]:
    root = insert(root, k)
print(preorder(root, []))   # [30, 20, 10, 25, 40, 50]
print(root.height)          # 3
class Node {
  constructor(key) {
    this.key = key;
    this.left = null;
    this.right = null;
    this.height = 1;
  }
}

const height = (n) => (n ? n.height : 0);
const update = (n) => { n.height = 1 + Math.max(height(n.left), height(n.right)); };
const balance = (n) => height(n.left) - height(n.right);

function rotateRight(y) {
  const x = y.left;
  y.left = x.right;
  x.right = y;
  update(y);
  update(x);
  return x;
}

function rotateLeft(x) {
  const y = x.right;
  x.right = y.left;
  y.left = x;
  update(x);
  update(y);
  return y;
}

function insert(node, key) {
  if (node === null) return new Node(key);
  if (key < node.key) node.left = insert(node.left, key);
  else if (key > node.key) node.right = insert(node.right, key);
  else return node;

  update(node);
  const b = balance(node);
  if (b > 1 && key < node.left.key) return rotateRight(node); // LL
  if (b < -1 && key > node.right.key) return rotateLeft(node); // RR
  if (b > 1) { // LR
    node.left = rotateLeft(node.left);
    return rotateRight(node);
  }
  if (b < -1) { // RL
    node.right = rotateRight(node.right);
    return rotateLeft(node);
  }
  return node;
}

function preorder(n, out = []) {
  if (n) {
    out.push(n.key);
    preorder(n.left, out);
    preorder(n.right, out);
  }
  return out;
}

let root = null;
for (const k of [10, 20, 30, 40, 50, 25]) root = insert(root, k);
console.log(preorder(root).join(', ')); // 30, 20, 10, 25, 40, 50
console.log(root.height); // 3
import java.util.ArrayList;
import java.util.List;

public class Main {
    static class Node {
        int key, height = 1;
        Node left, right;
        Node(int key) { this.key = key; }
    }

    static int height(Node n) { return n == null ? 0 : n.height; }
    static void update(Node n) { n.height = 1 + Math.max(height(n.left), height(n.right)); }
    static int balance(Node n) { return height(n.left) - height(n.right); }

    static Node rotateRight(Node y) {
        Node x = y.left;
        y.left = x.right;
        x.right = y;
        update(y);
        update(x);
        return x;
    }

    static Node rotateLeft(Node x) {
        Node y = x.right;
        x.right = y.left;
        y.left = x;
        update(x);
        update(y);
        return y;
    }

    static Node insert(Node node, int key) {
        if (node == null) return new Node(key);
        if (key < node.key) node.left = insert(node.left, key);
        else if (key > node.key) node.right = insert(node.right, key);
        else return node;

        update(node);
        int b = balance(node);
        if (b > 1 && key < node.left.key) return rotateRight(node);   // LL
        if (b < -1 && key > node.right.key) return rotateLeft(node);  // RR
        if (b > 1) {                                                  // LR
            node.left = rotateLeft(node.left);
            return rotateRight(node);
        }
        if (b < -1) {                                                 // RL
            node.right = rotateRight(node.right);
            return rotateLeft(node);
        }
        return node;
    }

    static void preorder(Node n, List<Integer> out) {
        if (n == null) return;
        out.add(n.key);
        preorder(n.left, out);
        preorder(n.right, out);
    }

    public static void main(String[] args) {
        Node root = null;
        for (int k : new int[] {10, 20, 30, 40, 50, 25}) root = insert(root, k);
        List<Integer> keys = new ArrayList<>();
        preorder(root, keys);
        System.out.println(keys);         // [30, 20, 10, 25, 40, 50]
        System.out.println(root.height);  // 3
    }
}
package main

import "fmt"

type Node struct {
	Key, Height int
	Left, Right *Node
}

func height(n *Node) int {
	if n == nil {
		return 0
	}
	return n.Height
}

func update(n *Node) { n.Height = 1 + max(height(n.Left), height(n.Right)) }

func balance(n *Node) int { return height(n.Left) - height(n.Right) }

func rotateRight(y *Node) *Node {
	x := y.Left
	y.Left = x.Right
	x.Right = y
	update(y)
	update(x)
	return x
}

func rotateLeft(x *Node) *Node {
	y := x.Right
	x.Right = y.Left
	y.Left = x
	update(x)
	update(y)
	return y
}

func insert(node *Node, key int) *Node {
	if node == nil {
		return &Node{Key: key, Height: 1}
	}
	if key < node.Key {
		node.Left = insert(node.Left, key)
	} else if key > node.Key {
		node.Right = insert(node.Right, key)
	} else {
		return node
	}

	update(node)
	b := balance(node)
	switch {
	case b > 1 && key < node.Left.Key: // LL
		return rotateRight(node)
	case b < -1 && key > node.Right.Key: // RR
		return rotateLeft(node)
	case b > 1: // LR
		node.Left = rotateLeft(node.Left)
		return rotateRight(node)
	case b < -1: // RL
		node.Right = rotateRight(node.Right)
		return rotateLeft(node)
	}
	return node
}

func preorder(n *Node, out []int) []int {
	if n == nil {
		return out
	}
	out = append(out, n.Key)
	out = preorder(n.Left, out)
	return preorder(n.Right, out)
}

func main() {
	var root *Node
	for _, k := range []int{10, 20, 30, 40, 50, 25} {
		root = insert(root, k)
	}
	fmt.Println(preorder(root, nil)) // [30 20 10 25 40 50]
	fmt.Println(root.Height)         // 3
}
#include <algorithm>
#include <iostream>
#include <vector>

struct Node {
    int key, height = 1;
    Node *left = nullptr, *right = nullptr;
    explicit Node(int k) : key(k) {}
};

int height(Node* n) { return n ? n->height : 0; }
void update(Node* n) { n->height = 1 + std::max(height(n->left), height(n->right)); }
int balance(Node* n) { return height(n->left) - height(n->right); }

Node* rotateRight(Node* y) {
    Node* x = y->left;
    y->left = x->right;
    x->right = y;
    update(y);
    update(x);
    return x;
}

Node* rotateLeft(Node* x) {
    Node* y = x->right;
    x->right = y->left;
    y->left = x;
    update(x);
    update(y);
    return y;
}

Node* insert(Node* node, int key) {
    if (!node) return new Node(key);
    if (key < node->key) node->left = insert(node->left, key);
    else if (key > node->key) node->right = insert(node->right, key);
    else return node;

    update(node);
    int b = balance(node);
    if (b > 1 && key < node->left->key) return rotateRight(node);   // LL
    if (b < -1 && key > node->right->key) return rotateLeft(node);  // RR
    if (b > 1) {                                                    // LR
        node->left = rotateLeft(node->left);
        return rotateRight(node);
    }
    if (b < -1) {                                                   // RL
        node->right = rotateRight(node->right);
        return rotateLeft(node);
    }
    return node;
}

void preorder(Node* n, std::vector<int>& out) {
    if (!n) return;
    out.push_back(n->key);
    preorder(n->left, out);
    preorder(n->right, out);
}

void destroy(Node* n) {
    if (!n) return;
    destroy(n->left);
    destroy(n->right);
    delete n;
}

int main() {
    Node* root = nullptr;
    for (int k : {10, 20, 30, 40, 50, 25}) root = insert(root, k);
    std::vector<int> keys;
    preorder(root, keys);
    for (int k : keys) std::cout << k << ' ';   // 30 20 10 25 40 50
    std::cout << '\n' << root->height << '\n';  // 3
    destroy(root);
}

LeetCode 練習題

用到這一演算法的經典題目,適合在玩過本實驗室後動手練習。連結將開啟 LeetCode。

如何選擇旋轉

  • LL(平衡因子 +2,左孩子 ≥ 0):一次右旋。
  • RR(平衡因子 −2,右孩子 ≤ 0):一次左旋。
  • LR(平衡因子 +2,左孩子 < 0):先對左孩子左旋,再對該節點右旋。
  • RL(平衡因子 −2,右孩子 > 0):先對右孩子右旋,再對該節點左旋。

AVL 樹與紅黑樹

AVL 樹平衡得更嚴格,查詢略快;紅黑樹允許更大的不平衡,更新時旋轉更少。因此很多標準庫(C++ std::map、Java TreeMap)採用紅黑樹,而讀多寫少的索引有時更偏向 AVL。

常見問題

解答您關心的工具使用與資料安全相關問題。

一次插入最多引起幾次旋轉?

最多一次單旋轉或一次雙旋轉。旋轉後該子樹的高度與插入前相同,上層無需再調整。

刪除呢?

刪除可能讓子樹變矮,所以可能一路到根的每一層都需要旋轉,最壞 O(log n) 次。

旋轉會破壞搜尋樹的順序嗎?

不會。旋轉只改變誰是父節點,鍵的中序序列完全不變。

使用該工具時我的資料安全嗎?

絕對安全。本工具採用 100% 純客戶端本地計算技術,所有資料與檔案均在您的本機瀏覽器記憶體中處理,絕不上傳到任何伺服器。