728x90
let bfs = function (node) {
let arr = [node]; //배열에 root노드를 넣음
let res = []; //value값들 출력
let cur; //현재값
while(arr.length>0) { //배열에 값이 없을때까지 돌림
cur = arr[0]; //현재 값은 배열의 첫번째 노드
arr.shift(); //배열에서 제일 먼저 들어온 노드 제거
res.push(cur.value); //현재 노드의 값을 res 배열에 넣어줌
for(let i=0;i<cur.children.length;i++) { //자식 노드들을 다 넣어줌
arr.push(cur.children[i]);
}
}
return res; //값들 출력
};
let Node = function (value) {
this.value = value;
this.children = [];
};
Node.prototype.addChild = function (child) {
this.children.push(child);
return child;
};반응형
'BEB > algorithm' 카테고리의 다른 글
| javascript quicksort (0) | 2022.11.16 |
|---|---|
| Toy15 Prime Number (0) | 2022.11.15 |
| 11 powerSet (0) | 2022.11.09 |
| toy10 binarySearch (0) | 2022.11.08 |
| Toy8 - largestProductOfThree (0) | 2022.11.04 |
댓글