// DFS 풀이법
// 비교 연산 때문인지 속도가 느림
var maxDepth = function (root) {
if (!root) return 0;
root.depth = 1;
const stack = [root];
let depth = 1;
while (stack.length) {
const node = stack.pop();
if (node.children) {
[...node.children].forEach((childNode) => {
childNode.depth = node.depth + 1;
if (depth < childNode.depth) depth = childNode.depth;
stack.push(childNode);
});
}
}
return depth;
};
// BFS 풀이법
// 최대값을 구하는 문제이므로 BFS가 더
var maxDepth = function (root) {
if (!root) return 0;
const stack = [root];
let depth = 1;
let children = 1;
while (stack.length) {
while (children) {
const node = stack.shift();
children--;
if (node.children) stack.push(...node.children);
}
children = stack.length;
depth++;
}
return --depth;
};
// children 변수를 만들 필요 없이, while문 내에서 stack.length를 활용하면 됐음.
var maxDepth = function (root) {
if (!root) return 0;
const stack = [root];
let depth = 0;
while (stack.length) {
const children = stack.length;
for (let i = 0; i < children; i++) {
const node = stack.shift();
if (node.children) stack.push(...node.children);
}
depth++;
}
return depth;
};
Level
LeetCode Easy