AVL木ビジュアライザー
自己平衡二分探索木のLL、RR、LR、RL回転アニメーション。
このツールについて
AVL 木は自分で平衡を保つ二分探索木です。各ノードは自分の高さを記録し、平衡係数(左部分木の高さ − 右部分木の高さ)は −1 から +1 の範囲に収まっていなければなりません。挿入や削除でこの範囲を外れたノードが出ると、1 回または 2 回の回転で元に戻すので、高さが約 1.44·log₂ n を超えることはありません。
このラボはすべてのノードの平衡係数を表示し、根へ戻る途中で最初に平衡を崩したノードをハイライトし、適用する回転のケース(LL、RR、LR、RL)を示します。木の形がなぜ変わるのかを正確に追えます。
使い方 AVL木ビジュアライザー
- キーを 1 つずつ挿入するか、整列済みの数列を挿入するプリセットを使います。普通の BST をだめにする入力です。
- 挿入のたびに平衡係数が更新される様子を見ます。赤い ±2 は回転が必要なノードの印です。
- 回転のステップを追います。ステータス行にケースと関係するノードが表示されます。
- キーの削除も試しましょう。挿入と違い、削除では根へ向かう途中の複数の段で回転が起こることがあります。
使用例
RR ケース
10, 20, 30 を挿入
ノード 10 の平衡係数が −2 → 左回転 1 回 → 20 が根になり、子は 10 と 30
LR ケース
30, 10, 20 を挿入
10 で左回転し、続いて 30 で右回転 → 根は 20
整列済みの入力でも浅いまま
1 … 15 を順に挿入
15 ノードの鎖ではなく、高さ 4 の完全な木になる
5 つの言語による実装
同じアルゴリズムを 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):右回転 1 回。
- RR(平衡係数 −2、右の子 ≤ 0):左回転 1 回。
- LR(平衡係数 +2、左の子 < 0):左の子を左回転してから、ノードを右回転。
- RL(平衡係数 −2、右の子 > 0):右の子を右回転してから、ノードを左回転。
AVL 木と赤黒木
AVL 木はより厳密に平衡を保つため、検索がわずかに速くなります。赤黒木はより大きな偏りを許し、更新時の回転が少なくて済みます。そのため多くの標準ライブラリ(C++ の std::map、Java の TreeMap)は赤黒木を使い、読み取り中心のインデックスでは AVL 木が好まれることもあります。
よくある質問
ツールの仕様やセキュリティに関する疑問にお答えします。
1 回の挿入で何回回転が起こりますか?
多くても単回転 1 回か二重回転 1 回です。回転後の部分木は挿入前と同じ高さになるので、それより上を直す必要はありません。
削除の場合は?
削除は部分木を低くすることがあるため、根までのすべての段で回転が必要になる可能性があります。最悪の場合 O(log n) 回です。
回転すると探索木の順序が崩れませんか?
崩れません。回転で変わるのはどのノードが親になるかだけで、キーの中間順の並びはまったく同じままです。
入力したデータやファイルは安全ですか?
完全に安全です。本ツールは100%ブラウザ内部で動作し、データがサーバーに送信されることは一切ありません。
関連ツール
注目のプロダクト tech-fun.net
便利なAI・生産性ツールとゲーム
Nihongo GameBox
Master Japanese typing, Kana, and JLPT N5–N1 vocabulary through interactive retro arcade games.
ResumeGPT
Tailors CVs and cover letters to every job opportunity with a multi-agent LLM pipeline, job tracking, and scheduled discovery.
CollectMind
Turns your bookmarks into a searchable AI knowledge base — entirely on-device, powered by Chrome's built-in Gemini Nano.