インタラクティブラボブラウザで動作

二分探索木ラボ

二分探索木(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)はキーを整列した順序で保ちます。あるノードの左部分木のキーはすべてそのノードより小さく、右部分木のキーはすべて大きい、というルールです。このルールひとつで、探索・挿入・削除にかかる時間は木の高さに比例し、中間順(in-order)でたどるとキーが昇順に並びます。

このラボでは各操作をステップごとにアニメーションで表示します。どの比較で探索が左右に進んだのか、新しいキーがどこにつながるのか、削除の 3 つのケースがどう処理されるのか、そして前順・中間順・後順・レベル順の走査がどの順にノードを訪れるのかが見えます。

使い方 二分探索木ラボ

  1. 数値を入力し、挿入・探索・削除のいずれかを選びます。アニメーションは自動で再生され、一時停止してステップボタンで前後に移動できます。
  2. ハイライトされたノードとステータス行に注目します。各ステップで、どんな比較をしてなぜ左(右)へ進んだのかを説明します。
  3. 走査を実行すると、木の下に訪問順が少しずつ並んでいきます。
  4. キーを昇順(1, 2, 3, 4, …)に挿入すると、木が連結リストのように退化します。AVL 木のラボと比べてみましょう。

使用例

探索の経路

入力
50, 30, 70, 20, 40, 60, 80 から作った木で 60 を探索
結果
50 → 右 → 70 → 左 → 60(3 回の比較で発見)

子を 2 つ持つノードの削除

入力
上の木から 50 を削除
結果
50 を中間順の後続ノード 60 で置き換え、右部分木から 60 を削除する

中間順の先行ノード(左側で最大のキー)を使っても同じく正しい結果になります。

走査

入力
同じ木
結果
中間順:20 30 40 50 60 70 80 · 前順:50 30 20 40 70 60 80 · レベル順:50 30 70 20 40 60 80

5 つの言語による実装

同じアルゴリズムを 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(英語)です。

削除の 3 つのケース

  • 葉:そのまま取り除きます。
  • 子が 1 つ:そのノードを唯一の子で置き換えます。
  • 子が 2 つ:中間順の後続ノード(右部分木の最小キー)をノードにコピーし、その後続ノードを削除します。後続ノードの子は多くても 1 つです。

高さが重要な理由

どの操作も根から葉への 1 本の経路をたどるので、コストは O(h) です。ランダムな順序で挿入すると期待される高さは約 2.99·log₂ n ですが、整列済みの入力では h = n となり、すべての操作が線形時間になります。AVL 木や赤黒木のような自己平衡木は、回転を加えて h = O(log n) を保ちます。

よくある質問

ツールの仕様やセキュリティに関する疑問にお答えします。

重複したキーはどう扱われますか?

このラボでは、すでに存在するキーは無視します。実際の実装では、重複を拒否するか、ノードに個数を持たせるか、等しいキーを常に片側へ送るかのいずれかです。

どの走査を使えばよいですか?

整列した出力には中間順、木のコピーやシリアライズには前順、親より先に子を解放・評価するとき(式の木など)は後順、幅優先で処理するならレベル順です。

BST と二分ヒープは同じものですか?

違います。ヒープが保証するのは親が子より大きい(または小さい)ことだけで、効率的な探索はできません。BST は左右の部分木を順序付けており、順序に基づく問い合わせに対応できます。

入力したデータやファイルは安全ですか?

完全に安全です。本ツールは100%ブラウザ内部で動作し、データがサーバーに送信されることは一切ありません。