class Node {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
class BinaryTree {
constructor() {
this.root = null;
}
// Self, L, R
#preOrder(node) {
if (node) {
process.stdin.write(node.value + ' > ');
this.#preOrder(node.left);
this.#preOrder(node.right);
}
}
traversePreOrder() {
process.stdin.write('PreOrder: ');
this.#preOrder(this.root);
console.log();
}
// L, Self, R
#inOrder(node) {
if (node) {
this.#inOrder(node.left);
process.stdin.write(node.value + ' > ');
this.#inOrder(node.right);
}
}
traverseInOrder() {
process.stdin.write('InOrder: ');
this.#inOrder(this.root);
console.log();
}
// L, R, Self
#postOrder(node) {
if (node) {
this.#postOrder(node.left);
this.#postOrder(node.right);
process.stdin.write(node.value + ' > ');
}
}
traversePostOrder() {
process.stdin.write('PostOrder: ');
this.#postOrder(this.root);
console.log();
}
// Stack 이용
dfs() {
process.stdin.write('DFS: ');
const stack = [];
stack.push(this.root);
while (stack.length > 0) {
const node = stack.pop();
if (node) {
process.stdin.write(node.value + ' > ');
stack.push(node.right);
stack.push(node.left);
}
}
console.log();
}
// Queue 이용
bfs() {
process.stdin.write('BFS: ');
const queue = [];
queue.push(this.root);
while (queue.length > 0) {
const node = queue.shift();
if (node) {
process.stdin.write(node.value + ' > ');
queue.push(node.left);
queue.push(node.right);
}
}
console.log();
}
// Tree의 높이
#height(node) {
if (!node) return 0;
return Math.max(this.#height(node.left), this.#height(node.right)) + 1;
}
height() {
return this.#height(this.root);
}
}
/*
A
B C
D E F G
H I J
*/
// Simple Test Cases
const bt = new BinaryTree();
bt.root = new Node('A');
const node1 = new Node('B');
const node2 = new Node('C');
const node3 = new Node('D');
const node4 = new Node('E');
const node5 = new Node('F');
const node6 = new Node('G');
const node7 = new Node('H');
const node8 = new Node('I');
const node9 = new Node('J');
bt.root.left = node1;
bt.root.right = node2;
node1.left = node3;
node1.right = node4;
node2.left = node5;
node2.right = node6;
node3.right = node7;
node5.left = node8;
node5.right = node9;
bt.traversePreOrder();
bt.traverseInOrder();
bt.traversePostOrder();
bt.dfs();
bt.bfs();
console.log(bt.height());
자세한 내용은 추후 업데이트 하겠습니다
반응형
'Aaron[에런] > Topic Keyword Articles' 카테고리의 다른 글
[Topic #자료구조 05] Recursion 대표 4가지 유형 구현 with JavaScript (0) | 2022.10.01 |
---|---|
[Topic #자료구조 04] Max/Min heap 구현 with JavaScript (0) | 2022.09.26 |
[Topic #자료구조 02] Singly Linked List 구현 with JavaScript (0) | 2022.09.06 |
[Topic #React 01] map 순수 함수 사용 시 key prop은 unique id로 설정! (0) | 2022.04.30 |
[Topic #자료구조 01] Array를 이용한 List 구현 with JavaScript (0) | 2022.01.07 |
댓글