트리 형태의 input값이 들어오면 레벨순으로 값을 저장하는 문제다.
BFS를 사용하여 레벨단위로 탐색하였다.
var levelOrder = function(root) {
const answer = [];
const q = [];
let lv = 0;
let tmp = [];
if(root)
q.push([root.val, root.children, 0]);
while(q.length) {
const [val, children, level] = q.shift();
console.log(val, children)
if(val === null) continue;
if(lv !== level) {
answer.push([...tmp]);
tmp = [];
lv = level;
}
tmp.push(val)
for(let c of children) {
q.push([c.val, c.children, level + 1])
}
}
if(tmp.length) answer.push([...tmp]);
return answer;
};
BFS로 최단 거리를 구하는 문제만 풀다가 다른 유형의 문제를 풀어보니 새로웠다.