js 如何遍历树的深度(高度)

使用栈遍历,非递归

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))

posted @ 2022-01-05 10:08  JoVee  阅读(489)  评论(0编辑  收藏  举报