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));
let output = bfs(root);
console.log(output); // --> [1, 2, 3, 4, 5]
leaf1.addChild(new Node(6));
rootChild2.addChild(new Node(7));
output = bfs(root);
console.log(output); // --> [1, 2, 3, 4, 5, 7, 6]
BFS는 노드의 같은 너비에 있는 자식들을 순회하는 방법이므로 queue를 통해 노드를 저장하고, value를 따로 저장하는 queue를 만든다.
let bfs = function (node) {
// TODO: 여기에 코드를 작성합니다.
let queue = [node]
let values = [node.value]
while(queue.length > 0 ){
const head = queue.shift()
for(let i=0;i<head.children.length;i++){
values.push(head.children[i].value)
queue.push(head.children[i])
}
}
return values
};
코드를 작성하고 디버깅을 통해서 queue에 담겨있는 노드를 꺼내 그 자식의 value를 배열에 담고 자식노드를 queue에 담음으로써 루트와 같은 너비에 있는 자식노드를 먼저 탐색할 수 있음을 이해할 수 있었다.