본문 바로가기
Aaron[에런]/Topic Keyword Articles

[Topic #자료구조 03] Binary Tree with Traverse, DFS/BFS, height 구현 with JavaScript

by Aaron-Kim 2022. 9. 12.
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());

자세한 내용은 추후 업데이트 하겠습니다

반응형

댓글