
📅 2025-11-03
➡️ 트리 알고리즘에 대해 새롭게 알게 된 것 또는 헷갈리는 부분 정리
배열 → 인덱스로 접근 가능한 연속적인 데이터 집합
연결 리스트 → 포인터로 노드를 연결한 비연속적 구조
스택 → 후입선출
큐 → 후입선출






삽입 → O(logn)
삭제 → O(logn)
트리 전체 순회 → O(n)



// 이진 트리의 노드 구조 정의
class Node {
constructor(data) {
this.data = data; // 실제 노드가 가진 값
this.left = null; // 왼쪽 자식 노드
this.right = null; // 오른쪽 자식 노드
}
}
// 이진 트리 클래스
class Tree {
constructor() {
this.root = null; // 루트 노드
}
makeTree(array, start = 0, end = array.length - 1) {
if (start > end) return null;
const mid = Math.floor((start + end) / 2);
const newNode = new Node(array[mid]);
newNode.left = this.makeTree(array, start, mid - 1); // 왼쪽 서브트리 생성
newNode.right = this.makeTree(array, mid + 1, end); // 오른쪽 서브트리 생성
this.root = newNode;
return newNode;
}
search(node, value) {
if (!node) return console.log('노드 없음');
if (value < node.data) {
// 왼쪽
console.log(`${value}값이 ${node.data}보다 작다 → 왼쪽으로 이동`);
this.search(node.left, value);
} else if (value > node.data) {
// 오른쪽
console.log(`${value}값이 ${node.data}보다 크다 → 오른쪽으로 이동`);
this.search(node.right, value);
} else {
// 데이터 찾음
console.log(`데이터(${value}) 찾음`);
}
}
}
const t = new Tree();
t.makeTree([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
// console.log(JSON.stringify(t, null, 4));
t.search(t.root, 6);
// 이진 트리의 노드 구조 정의
class Node {
constructor(data) {
this.data = data; // 실제 노드가 가진 값
this.left = null; // 왼쪽 자식 노드
this.right = null; // 오른쪽 자식 노드
}
}
class Tree {
constructor() {
this.root = null; // 루트 노드
}
// 노드 삽입
insert(value) {
const newNode = new Node(value);
if (!this.root) {
this.root = newNode;
return;
}
const insertNode = (node, value) => {
if (!node) return newNode;
if (value < node.data) {
node.left = insertNode(node.left, value); // 왼쪽 서브트리에 삽입
} else if (value > node.data) {
node.right = insertNode(node.right, value); // 오른쪽 서브트리에 삽입
}
return node;
};
this.root = insertNode(this.root, value);
}
// 노드 탐색
search(node, value) {
if (!node) {
console.log('노드 없음');
return null;
}
if (value < node.data) {
console.log(`${value} 값이 ${node.data}보다 작음 → 왼쪽으로 이동`);
return this.search(node.left, value);
} else if (value > node.data) {
console.log(`${value} 값이 ${node.data}보다 큼 → 오른쪽으로 이동`);
return this.search(node.right, value);
} else {
console.log(`${value} 찾음`);
return node;
}
}
// 중위 순회 - Left → Root → Right
inOrder(node) {
if (!node) return;
this.inOrder(node.left);
console.log(node.data);
this.inOrder(node.right);
}
// 전위 순회 - Root → Left → Right
preOrder(node) {
if (!node) return;
console.log(node.data);
this.preOrder(node.left);
this.preOrder(node.right);
}
// 후위 순회 - Left → Right → Root
postOrder(node) {
if (!node) return;
this.postOrder(node.left);
this.postOrder(node.right);
console.log(node.data);
}
}
const t = new Tree();
t.insert(6);
t.insert(4);
t.insert(8);
t.insert(2);
t.insert(5);
t.insert(7);
t.insert(9);
console.log(t.root);
t.search(t.root, 5);
console.log('중위 순회 결과:');
t.inOrder(t.root);
console.log('전위 순회 결과:');
t.preOrder(t.root);
console.log('후위 순회 결과:');
t.postOrder(t.root);