- 트리를 구성하는 Node 중 하나의 Node 객체를 입력받아서 해당노드를 시작으로 BFS를 한다.
- node.value(number 타입), node.children(Node를 요소로 갖는 배열)
- 아래와 같이 value를 입력받아 그 자식노드들을 트리 형태로 만들었다.
let bfs = (node) => {
}
let Node = (value) => {
this.value = value;
this.children = [];
}
Node.prototype.addChild = (child) => {
this.children.push(child);
return child;
}
- 예시를 통해 알아보면 다음과 같다.
- 아래와 같이 노드들을 생성했을 경우 그림과 같은 형태로 노드들이 생성된다.
let root = new Node(1);
let rootChild1 = root.addChild(new Node(2));
let rootChild2 = root.addChild(new Node(3));
let leaf1 = rootChild1.addChild(new Node(4));
let leaf2 = rootChild1.addChild(new Node(5));

- 그럼 최종적으로 [1, 2, 3, 4, 5]의 형태로 출력되게 만들어줘야한다.
- BFS는 너비 우선이기 때문에 재귀적인 방법을 사용할 수 없다.
- 따라서 Queue의 개념을 사용하여 차례대로 출력되게끔 해줘야한다.
let bfs = (node) => {
// 최종적으로 리턴할 배열 변수를 만들어준다.
let result = [];
// 큐를 만들어준다. -> 큐에 초기 node값을 넣어둔다. -> queue = [1]
let queue = [node]
// 큐의 길이가 0보다 클때까지 while문을 돌려준다.
while(queue.length > 0) {
// queue의 0번째 인덱스 요소를 담아둘 변수를 만들어준다. -> head = 1
let head = queue[0];
// 큐는 head를 제외한 나머지로 세팅해준다. -> queue = []
queue = queue.slice(1);
// result에 head.value(node.value)를 넣어준다.
result.push(head.value);
// head(node)의 children을 탐색해서 큐에 넣어준다. -> queue = [2, 3]
head.children.forEach((el) => queue.push(el))
}
return result;
}
let Node = (value) => {
this.value = value;
this.children = [];
}
Node.prototype.addChild = (child) => {
this.children.push(child);
return child;
}