Coding Interview

[기초] BFS와 DFS

milliwonkim 2022. 9. 22. 19:50
반응형
SMALL
class Node {
  constructor(data) {
    this.data = data;
    this.children = [];
  }

  add(data) {
    this.children.push(new Node(data));
  }

  remove(data) {
    this.children = this.children.filter((child) =>
      child.data === data ? false : true
    );
  }
}

class Tree {
  constructor() {
    this.root = null;
  }

  BFS(fn) {
    if (this.root === null) return;
    const unvisitedQueue = [this.root];
    while (unvisitedQueue.length !== 0) {
      const current = unvisitedQueue.shift();
      unvisitedQueue.push(...current.children);
      fn(current);
    }
  }

  DFS(fn) {
    if (this.root === null) return null;
    const unvisitedList = [this.root];
    while (unvisitedList.length !== 0) {
      const current = unvisitedList.shift();
      unvisitedList.unshift(...current.children);
      fn(current);
    }
  }
}

// ------------------------------------

const t = new Tree();
t.root = new Node("a");
t.root.add("b");
t.root.children[0].add("c");
t.root.add("d");

const BFSArray = [];
const DFSArray = [];

t.BFS((node) => BFSArray.push(node.data));
t.DFS((node) => DFSArray.push(node.data));

console.log("BFS: ", BFSArray);
console.log("DFS: ", DFSArray);
console.log("TREE: ", t.root);
반응형
LIST