이진 탐색 트리 랩
BST 노드 삽입, 삭제 및 순회 경로 인터랙티브 시각화.
이 도구에 대하여
이진 탐색 트리(BST)는 키를 정렬된 순서로 유지합니다. 어떤 노드의 왼쪽 서브트리에 있는 키는 모두 그 노드보다 작고, 오른쪽 서브트리의 키는 모두 큽니다. 이 규칙 하나 덕분에 탐색·삽입·삭제에 걸리는 시간이 트리의 높이에 비례하고, 중위 순회를 하면 키가 정렬된 순서로 나옵니다.
이 실험실은 각 연산을 단계별 애니메이션으로 보여 줍니다. 어떤 비교 때문에 탐색이 왼쪽이나 오른쪽으로 가는지, 새 키가 어디에 붙는지, 삭제의 세 가지 경우를 어떻게 처리하는지, 전위·중위·후위·레벨 순회가 어떤 순서로 노드를 방문하는지 볼 수 있습니다.
사용 방법 이진 탐색 트리 랩
- 숫자를 입력하고 삽입, 탐색, 삭제 중 하나를 고릅니다. 애니메이션이 자동으로 재생되며, 일시 정지한 뒤 단계 버튼으로 앞뒤로 이동할 수 있습니다.
- 강조된 노드와 상태 표시줄을 보세요. 각 단계마다 어떤 비교를 했고 왜 왼쪽이나 오른쪽으로 갔는지 설명합니다.
- 순회를 실행하면 트리 아래에 방문 순서가 차례로 쌓입니다.
- 키를 정렬된 순서(1, 2, 3, 4, …)로 삽입하면 트리가 연결 리스트처럼 퇴화합니다. AVL 트리 실험실과 비교해 보세요.
사용 예시
탐색 경로
50, 30, 70, 20, 40, 60, 80으로 만든 트리에서 60 탐색
50 → 오른쪽 → 70 → 왼쪽 → 60 (3번 비교 만에 발견)
자식이 둘인 노드 삭제
위 트리에서 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(영어)로 연결됩니다.
삭제의 세 가지 경우
- 리프: 그냥 제거합니다.
- 자식이 하나: 노드를 그 유일한 자식으로 대체합니다.
- 자식이 둘: 중위 후속자(오른쪽 서브트리의 최솟값)를 노드에 복사한 뒤 후속자를 삭제합니다. 후속자의 자식은 많아야 하나입니다.
높이가 중요한 이유
모든 연산은 루트에서 리프까지 하나의 경로를 따르므로 비용은 O(h)입니다. 무작위 순서로 삽입하면 기대 높이는 약 2.99·log₂ n이지만, 정렬된 입력에서는 h = n이 되어 모든 연산이 선형 시간이 됩니다. AVL 트리나 레드-블랙 트리 같은 자가 균형 트리는 회전을 더해 h = O(log n)을 유지합니다.
자주 묻는 질문
도구 이용과 데이터 보안에 관한 궁금증을 확인하세요.
중복 키는 어떻게 처리하나요?
이 실험실은 이미 있는 키를 무시합니다. 실제 구현은 중복을 거부하거나, 노드에 개수를 저장하거나, 같은 키를 항상 한쪽으로 보냅니다.
어떤 순회를 써야 하나요?
정렬된 출력에는 중위, 트리 복사나 직렬화에는 전위, 부모보다 자식을 먼저 해제·계산할 때(예: 수식 트리)는 후위, 너비 우선 처리에는 레벨 순회를 씁니다.
BST와 이진 힙은 같은 것인가요?
아닙니다. 힙은 부모가 자식보다 크다(또는 작다)는 것만 보장하므로 효율적으로 탐색할 수 없습니다. BST는 왼쪽과 오른쪽 서브트리를 정렬해 순서 기반 질의를 지원합니다.
내 데이터는 안전하게 보호되나요?
네, 완벽하게 안전합니다. 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.