交互实验室在浏览器中运行

二叉搜索树实验室

二叉搜索树(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% 纯客户端本地计算技术,所有数据与文件均在您的本机浏览器内存中处理,绝不上传到任何远程服务器。