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

二元搜尋樹實驗室

二元搜尋樹(BST)動態插入、刪除與四序遍歷路徑動畫。

速度:
平衡的範例樹。可以插入、搜尋、刪除鍵,或執行一次走訪。
20304050607080
節點數: 7高度: 3理想最小高度: 3
虛擬碼
1insert(node, v):
2 if node is empty: create leaf v
3 if v == node.key: duplicate, stop
4 if v < node.key: insert(node.left, v)
5 else: insert(node.right, v)

關於本工具

二叉搜尋樹(BST)按順序儲存鍵:節點左子樹中的鍵都比它小,右子樹中的鍵都比它大。正是這條規則,讓查詢、插入和刪除的耗時與樹的高度成正比,而中序遍歷會按從小到大的順序輸出所有鍵。

本實驗室逐步演示每個操作:查詢時每次比較為何向左或向右,新鍵掛在哪裡,刪除的三種情況如何處理,以及前序、中序、後序和層序遍歷訪問節點的順序。

使用方法 二元搜尋樹實驗室

  1. 輸入一個數字,選擇插入、查詢或刪除。動畫會自動播放;可以暫停,用單步按鈕前後檢視。
  2. 關注高亮節點和狀態列:每一步都會說明做了什麼比較、為什麼向左或向右。
  3. 執行遍歷,觀察樹下方逐步生成的訪問順序。
  4. 按有序順序插入鍵(1、2、3、4……),會看到樹退化成連結串列,再去 AVL 樹實驗室對比一下。

範例

查詢路徑

輸入
由 50、30、70、20、40、60、80 構成的樹,查詢 60
結果
50 → 右 → 70 → 左 → 60(比較 3 次找到)

刪除有兩個孩子的節點

輸入
從上面的樹中刪除 50
結果
用中序後繼 60 替換 50,再從右子樹中刪除 60

用中序前驅(左子樹中最大的鍵)替換同樣正確。

遍歷

輸入
同一棵樹
結果
中序:20 30 40 50 60 70 80 · 前序:50 30 20 40 70 60 80 · 層序:50 30 70 20 40 60 80

五種語言的程式碼實作

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

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


def insert(root, key):
    if root is None:
        return Node(key)
    if key < root.key:
        root.left = insert(root.left, key)
    elif key > root.key:
        root.right = insert(root.right, key)
    return root  # duplicates are ignored


def search(root, key):
    while root is not None and root.key != key:
        root = root.left if key < root.key else root.right
    return root is not None


def delete(root, key):
    if root is None:
        return None
    if key < root.key:
        root.left = delete(root.left, key)
    elif key > root.key:
        root.right = delete(root.right, key)
    else:
        if root.left is None:
            return root.right
        if root.right is None:
            return root.left
        # Two children: copy the in-order successor, then delete it.
        succ = root.right
        while succ.left is not None:
            succ = succ.left
        root.key = succ.key
        root.right = delete(root.right, succ.key)
    return root


def inorder(root, out):
    if root is not None:
        inorder(root.left, out)
        out.append(root.key)
        inorder(root.right, out)
    return out


root = None
for k in [50, 30, 70, 20, 40, 60, 80]:
    root = insert(root, k)
print(inorder(root, []))   # [20, 30, 40, 50, 60, 70, 80]
print(search(root, 60))    # True
root = delete(root, 30)
print(inorder(root, []))   # [20, 40, 50, 60, 70, 80]
class Node {
  constructor(key) {
    this.key = key;
    this.left = null;
    this.right = null;
  }
}

function insert(root, key) {
  if (root === null) return new Node(key);
  if (key < root.key) root.left = insert(root.left, key);
  else if (key > root.key) root.right = insert(root.right, key);
  return root; // duplicates are ignored
}

function search(root, key) {
  while (root !== null && root.key !== key) {
    root = key < root.key ? root.left : root.right;
  }
  return root !== null;
}

function remove(root, key) {
  if (root === null) return null;
  if (key < root.key) root.left = remove(root.left, key);
  else if (key > root.key) root.right = remove(root.right, key);
  else {
    if (root.left === null) return root.right;
    if (root.right === null) return root.left;
    // Two children: copy the in-order successor, then delete it.
    let succ = root.right;
    while (succ.left !== null) succ = succ.left;
    root.key = succ.key;
    root.right = remove(root.right, succ.key);
  }
  return root;
}

function inorder(root, out = []) {
  if (root !== null) {
    inorder(root.left, out);
    out.push(root.key);
    inorder(root.right, out);
  }
  return out;
}

let root = null;
for (const k of [50, 30, 70, 20, 40, 60, 80]) root = insert(root, k);
console.log(inorder(root).join(", ")); // 20, 30, 40, 50, 60, 70, 80
console.log(search(root, 60)); // true
root = remove(root, 30);
console.log(inorder(root).join(", ")); // 20, 40, 50, 60, 70, 80
import java.util.ArrayList;
import java.util.List;

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

    static Node insert(Node root, int key) {
        if (root == null) return new Node(key);
        if (key < root.key) root.left = insert(root.left, key);
        else if (key > root.key) root.right = insert(root.right, key);
        return root; // duplicates are ignored
    }

    static boolean search(Node root, int key) {
        while (root != null && root.key != key) {
            root = key < root.key ? root.left : root.right;
        }
        return root != null;
    }

    static Node delete(Node root, int key) {
        if (root == null) return null;
        if (key < root.key) root.left = delete(root.left, key);
        else if (key > root.key) root.right = delete(root.right, key);
        else {
            if (root.left == null) return root.right;
            if (root.right == null) return root.left;
            // Two children: copy the in-order successor, then delete it.
            Node succ = root.right;
            while (succ.left != null) succ = succ.left;
            root.key = succ.key;
            root.right = delete(root.right, succ.key);
        }
        return root;
    }

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

    public static void main(String[] args) {
        Node root = null;
        for (int k : new int[] {50, 30, 70, 20, 40, 60, 80}) root = insert(root, k);
        List<Integer> keys = new ArrayList<>();
        inorder(root, keys);
        System.out.println(keys);              // [20, 30, 40, 50, 60, 70, 80]
        System.out.println(search(root, 60));  // true
        root = delete(root, 30);
        keys.clear();
        inorder(root, keys);
        System.out.println(keys);              // [20, 40, 50, 60, 70, 80]
    }
}
package main

import "fmt"

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

func insert(root *Node, key int) *Node {
	if root == nil {
		return &Node{Key: key}
	}
	if key < root.Key {
		root.Left = insert(root.Left, key)
	} else if key > root.Key {
		root.Right = insert(root.Right, key)
	}
	return root // duplicates are ignored
}

func search(root *Node, key int) bool {
	for root != nil && root.Key != key {
		if key < root.Key {
			root = root.Left
		} else {
			root = root.Right
		}
	}
	return root != nil
}

func remove(root *Node, key int) *Node {
	if root == nil {
		return nil
	}
	switch {
	case key < root.Key:
		root.Left = remove(root.Left, key)
	case key > root.Key:
		root.Right = remove(root.Right, key)
	default:
		if root.Left == nil {
			return root.Right
		}
		if root.Right == nil {
			return root.Left
		}
		// Two children: copy the in-order successor, then delete it.
		succ := root.Right
		for succ.Left != nil {
			succ = succ.Left
		}
		root.Key = succ.Key
		root.Right = remove(root.Right, succ.Key)
	}
	return root
}

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

func main() {
	var root *Node
	for _, k := range []int{50, 30, 70, 20, 40, 60, 80} {
		root = insert(root, k)
	}
	fmt.Println(inorder(root, nil)) // [20 30 40 50 60 70 80]
	fmt.Println(search(root, 60))   // true
	root = remove(root, 30)
	fmt.Println(inorder(root, nil)) // [20 40 50 60 70 80]
}
#include <iostream>
#include <memory>
#include <vector>

struct Node {
    int key;
    std::unique_ptr<Node> left, right;
    explicit Node(int k) : key(k) {}
};

void insert(std::unique_ptr<Node>& root, int key) {
    if (!root) { root = std::make_unique<Node>(key); return; }
    if (key < root->key) insert(root->left, key);
    else if (key > root->key) insert(root->right, key);
    // duplicates are ignored
}

bool search(const Node* root, int key) {
    while (root && root->key != key) {
        root = key < root->key ? root->left.get() : root->right.get();
    }
    return root != nullptr;
}

void remove(std::unique_ptr<Node>& root, int key) {
    if (!root) return;
    if (key < root->key) remove(root->left, key);
    else if (key > root->key) remove(root->right, key);
    else if (!root->left) root = std::move(root->right);
    else if (!root->right) root = std::move(root->left);
    else {
        // Two children: copy the in-order successor, then delete it.
        Node* succ = root->right.get();
        while (succ->left) succ = succ->left.get();
        root->key = succ->key;
        remove(root->right, succ->key);
    }
}

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

void print(const std::unique_ptr<Node>& root) {
    std::vector<int> keys;
    inorder(root.get(), keys);
    for (int k : keys) std::cout << k << ' ';
    std::cout << '\n';
}

int main() {
    std::unique_ptr<Node> root;
    for (int k : {50, 30, 70, 20, 40, 60, 80}) insert(root, k);
    print(root);                                              // 20 30 40 50 60 70 80
    std::cout << std::boolalpha << search(root.get(), 60) << '\n'; // true
    remove(root, 30);
    print(root);                                              // 20 40 50 60 70 80
}

LeetCode 練習題

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

刪除的三種情況

  • 葉子節點:直接刪除。
  • 只有一個孩子:用這個孩子頂替該節點。
  • 有兩個孩子:把中序後繼(右子樹中最小的鍵)複製到該節點,再刪除後繼節點——它最多隻有一個孩子。

為什麼高度很重要

所有操作都只走一條從根到葉的路徑,所以代價是 O(h)。隨機插入時期望高度約為 2.99·log₂ n;但有序輸入會讓 h = n,每個操作都退化為線性。AVL 樹、紅黑樹等自平衡樹通過旋轉把高度保持在 O(log n)。

常見問題

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

重複的鍵怎麼處理?

本實驗室會忽略已存在的鍵。實際實現通常會拒絕重複、在節點中計數,或者把相等的鍵統一放到某一側。

該用哪種遍歷?

要有序輸出用中序;複製或序列化樹用前序;需要先處理孩子再處理父節點(如釋放記憶體、表示式求值)用後序;按層廣度優先處理用層序。

BST 和二叉堆是一回事嗎?

不是。堆只保證父節點比孩子大(或小),無法高效查詢;BST 規定了左右子樹的大小關係,支援有序查詢。

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

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