头条面试题:计算目录树的深度

时间:2022-07-24
本文章向大家介绍头条面试题:计算目录树的深度,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

题目:前端在后台管理系统经常会用到目录树,求下面目录tree的高度。

const tree = {
  name: 'root',
  children: [
    { name: '叶子1-1' },
    { name: '叶子1-2' },
    {
      name: '叶子2-1',
      children: [{
        name: '叶子3-1',
        children: [{
          name: '叶子4-1'
        }]
      }]
    }
  ]
}

function getDepth(tree) {
  let depth = 0

  if (tree) {
    let arr = [tree]
    let temp = arr
    while (temp.length) {
      arr = temp
      temp = []
      for (let i = 0; i < arr.length; i++) {
        if (arr[i].children && arr[i].children.length) {
          for (let j = 0; j < arr[i].children.length; j++) {
            temp.push(arr[i].children[j])
          }
        }
      }
      depth++
    }
  }
  return depth
}console.log(getDepth(tree)); //输出4

思路:

得出depth即为树的高度得出depth即为树

  1. 定义变量depth为0
  2. 定义一个空数组temp,然后遍历tree,如果tree有children,就push到temp里面
  3. 开始while循环,如果temp长度不为0,depth++;如果temp长度为0,停止
  4. 得出depth即为树的高度 得出depth即为树的高度得出depth即为树的高度得出depth即为树的高度