johnv

使用栈遍历,非递归

function getDepth(data = []) {
  let stack = [data]
  let depth = 0
  while (stack.length > 0) {
    let temp = []
    const list = stack.pop()

    if (list.length === 0) {
      continue
    }

    depth++
    // 思路:使用数组遍历的方式,消减树的层级
    list.forEach((item) => {
      if (item && Array.isArray(item.children)) {
        temp = temp.concat(...item.children)
      }
    })

    if (temp.length > 0) {
      stack.push(temp)
    }
  }
  return depth
}

测试代码

const tree = [
  {
    label: \'12月\',
    children: [
      {
        label: \'加分\',
      },
      {
        label: \'减分\',
        children: [
          {
            label: \'加分\',
          },
          {
            label: \'减分\',
          },
        ],
      },
    ],
  },
]
console.log(getDepth(tree))

分类:

技术点:

相关文章:

  • 2021-12-27
  • 2021-04-18
  • 2021-12-27
  • 2021-12-27
  • 2021-05-18
  • 2021-08-14
  • 2021-12-27
猜你喜欢
  • 2022-03-05
  • 2022-12-23
  • 2021-12-06
  • 2021-05-29
  • 2021-05-15
  • 2022-01-22
  • 2022-12-23
相关资源
相似解决方案