-
-
Notifications
You must be signed in to change notification settings - Fork 235
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
计算目录树的深度 #38
Comments
let max = 0;
function depth(tree, deep) {
if (tree.children === undefined || tree.name === undefined) {
max = deep > max ? deep : max;
return;
}
if (tree.children) {
tree.children.forEach((element) => {
depth(element, deep + 1);
});
}
}
depth(tree, 0);
console.log(max); |
function treeDepth(node) {
if (node === null) {
return 0;
} else {
const maxDepth = Math.max(...node.children.map(treeDepth));
return maxDepth + 1;
}
} |
// 1. Method1: DFS
function getDepth(tree) {
let depth = 0,
maxDepth = 0
traversal(tree)
return maxDepth
function traversal(node) {
if (!node) return
depth++
maxDepth = Math.max(maxDepth, depth)
node.children && node.children.forEach(el => {
traversal(el)
})
depth--
}
}
console.log(getDepth(tree))
// 2. Method2: BFS
function getDepthBFS(tree) {
let queue = [],
res = 0
if (tree) queue.push(tree)
while (queue.length) {
let levelCount = queue.length
res++
for (let i = 0; i < levelCount; i++) {
let node = queue.shift()
node.children && node.children.forEach(el => {
queue.push(el)
})
}
}
return res
}
console.log(getDepthBFS(tree)) |
function getLevel(tree) {
if(!(tree.children && tree.children.length)) {
return 1
}
const {children} = tree
let level = -Infinity
for(const c of children) {
level = Math.max(level, getLevel(c) + 1)
}
return level
} |
function getLevel(tree) {
if (!tree) return 0
if (tree.children && tree.children.length) {
let res = []
for (const item of tree.children) {
res.push(getLevel(item))
}
return Math.max(...res) + 1
}
return 1
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The text was updated successfully, but these errors were encountered: