728x90
문제
임의의 tree를 구성하는 노드 중 하나의 Node 객체를 입력받아, 해당 노드를 시작으로 너비 우선 탐색(BFS, Breadth First Search)을 합니다. 이 때, 탐색되는 순서대로 노드의 값이 저장된 배열을 리턴해야 합니다.
입력
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]
let bfs = function (node) {
// TODO: 여기에 코드를 작성합니다.
let queue = [node];
const values = [];
while (queue.length > 0) {
const head = queue[0];
queue = queue.slice(1);
values.push(head.value);
head.children.forEach((child) => queue.push(child));
}
return values;
};
// 이 아래 코드는 변경하지 않아도 됩니다. 자유롭게 참고하세요.
let Node = function (value) {
this.value = value;
this.children = [];
};
// 위 Node 객체로 구성되는 트리는 매우 단순한 형태의 트리입니다.
// membership check(중복 확인)를 따로 하지 않습니다.
Node.prototype.addChild = function (child) {
this.children.push(child);
return child;
};
728x90
'코플릿 > toyproblem' 카테고리의 다른 글
toy problem 15 (0) | 2021.10.29 |
---|---|
toy problem 13 (0) | 2021.10.29 |
toy problem 10 (0) | 2021.10.28 |
toy problem 11 (0) | 2021.10.28 |
toy problem 08 (0) | 2021.10.28 |