// 示例目录树对象
const directoryTree = {
name: "root",
children: [
{
name: "folder1",
children: [
{ name: "file1-1" },
{ name: "file1-2" },
{
name: "folder1-1",
children: [
{ name: "file1-1-1" },
{ name: "file1-1-2" }
]
}
]
},
{
name: "folder2",
children: [
{ name: "file2-1" },
{
name: "folder2-1",
children: [
{ name: "file2-1-1" },
{
name: "folder2-1-1",
children: [
{ name: "file2-1-1-1" }
]
}
]
}
]
}
]
};
// 计算目录树深度的函数
function calculateDepth(node) {
// 如果没有children属性,则深度为1
if (!node.children || node.children.length === 0) {
return 1;
}
// 递归计算每个子节点的深度,并返回最大深度+1(当前节点的深度)
return 1 + Math.max(...node.children.map(child => calculateDepth(child)));
}
// 使用函数计算目录树的深度
const depth = calculateDepth(directoryTree);
console.log("Directory tree depth:", depth); // 输出目录树的深度
console