트리는 계층적인 구조를 가진 비선형 자료구조입니다. 일반적으로 부모-자식 관계를 가지며, 루트 노드(Root Node)에서 시작해 여러 개의 자식 노드(Child Node)로 분기된다.
용어 | 설명 |
---|---|
루트(Root) 노드 | 트리의 최상위 노드 (부모가 없음) |
부모(Parent) 노드 | 다른 노드를 가리키는 노드 |
자식(Child) 노드 | 부모 노드에서 연결된 노드 |
형제(Sibling) 노드 | 같은 부모를 가진 노드들 |
리프(Leaf) 노드 | 자식이 없는 노드 |
서브트리(Subtree) | 하나의 노드를 기준으로 형성된 작은 트리 |
깊이(Depth) | 루트에서 특정 노드까지의 거리 |
높이(Height) | 특정 노드에서 가장 깊은 노드까지의 거리 |
차수(Degree) | 특정 노드가 가진 자식 노드의 개수 |
일반 트리 (General Tree)
이진 트리(Binary Tree)
class Node {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
const root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
이진 탐색 트리(Binary Search Tree, BST)
class BST {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
insert(value) {
if (value < this.value) {
if (this.left === null) {
this.left = new BST(value);
} else {
this.left.insert(value);
}
} else {
if (this.right === null) {
this.right = new BST(value);
} else {
this.right.insert(value);
}
}
}
}
const root = new BST(10);
root.insert(5);
root.insert(15);
균형 트리 (Balanced Tree)
힙(Heap) 트리
트리의 노드를 탐색하는 방법에는 DFS(깊이 우선 탐색)과 BFS(너비 우선 탐색)이 있다.
DFS (Depth First Search, 깊이 우선 탐색)
function inorderTraversal(node) {
if (node !== null) {
inorderTraversal(node.left);
console.log(node.value);
inorderTraversal(node.right);
}
}
inorderTraversal(root);
BFS (Breadth First Search, 너비 우선 탐색)
function bfsTraversal(root) {
let queue = [root];
while (queue.length > 0) {
let node = queue.shift();
console.log(node.value);
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
}
}
bfsTraversal(root);
Set
은 해시 테이블(Hash Table)을 기반으로 동작한다.Set.has(value)
연산은 매우 빠르게 수행된다.const mySet = new Set();
mySet.add(1);
mySet.add(2);
mySet.add(3);
console.log(mySet.has(2)); // true
console.log(mySet.size); // 3
const arr = [1, 2, 2, 3, 4, 4, 5];
const uniqueArr = [...new Set(arr)];
console.log(uniqueArr); // [1, 2, 3, 4, 5]
트리와 집합의 기본적인 개념은 직관적이라 쉬웠지만.. 조금만 파고들어가니 아니나 다를까 이건 또 뭔소리인가 싶었다.
트리는 예를 들자면 족보나 폴더 구조를 떠올려보면 쉽게 이해 할 수 있고 집합은 쇼핑할 때 장바구니나 누군가의 버킷리스트를 떠올려보면 쉽게 이해 할 수 있다.