인터랙티브 랩브라우저에서 실행

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 → 왼쪽 회전 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번입니다. 회전 후 서브트리는 삽입 전과 같은 높이가 되므로 그 위는 고칠 필요가 없습니다.

삭제는요?

삭제는 서브트리를 낮출 수 있으므로 루트까지 모든 층에서 회전이 필요할 수 있습니다. 최악의 경우 O(log n)번입니다.

회전하면 탐색 트리의 순서가 깨지지 않나요?

깨지지 않습니다. 회전은 어떤 노드가 부모인지만 바꿀 뿐, 키의 중위 순서는 그대로입니다.

내 데이터는 안전하게 보호되나요?

네, 완벽하게 안전합니다. 100% 브라우저 메모리 상에서만 동작하며 외부 서버로 일절 전송되지 않습니다.