[javascript] 그래프와 트리 알고리즘

그래프와 트리는 컴퓨터 과학과 소프트웨어 공학에서 중요한 개념입니다. 이들은 데이터 구조와 알고리즘에서 널리 사용되며 많은 문제들을 해결하는 데 활용됩니다.

그래프

다음은 간단한 그래프의 표현 방법을 보여주는 JavaScript 코드입니다.

class Graph {
  constructor() {
    this.vertices = [];
    this.adjacencyList = new Map();
  }

  addVertex(v) {
    this.vertices.push(v);
    this.adjacencyList.set(v, []);
  }

  addEdge(v, w) {
    this.adjacencyList.get(v).push(w);
    this.adjacencyList.get(w).push(v);
  }
}

트리

아래는 이진 탐색 트리를 구현하는 간단한 JavaScript 코드입니다.

class Node {
  constructor(data) {
    this.data = data;
    this.left = null;
    this.right = null;
  }
}

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

  insert(data) {
    let newNode = new Node(data);
    if (this.root === null) this.root = newNode;
    else this.insertNode(this.root, newNode);
  }

  insertNode(node, newNode) {
    if (newNode.data < node.data) {
      if (node.left === null) node.left = newNode;
      else this.insertNode(node.left, newNode);
    } else {
      if (node.right === null) node.right = newNode;
      else this.insertNode(node.right, newNode);
    }
  }
}

그래프와 트리 알고리즘은 다양한 분야에서 활용되며, 프로그래밍 공부를 할 때 중요한 개념이니 꼭 숙지해두시기를 권장드립니다.

더 많은 정보를 원하시면 다음 자료들을 참고하시기 바랍니다.