【2022-6-17】js遍历树结构的第一个无叶子节点的节点

这篇博客介绍了如何使用JavaScript通过递归、while循环和for循环三种方式遍历树形结构,查找并返回第一个没有子节点(叶子节点)的节点。示例代码展示了具体的实现细节,并提供了在实际数据结构`treeData`上的应用实例。
摘要由CSDN通过智能技术生成

js遍历树结构的第一个无叶子节点的节点

let treeData = [
  {
    id: '1',
    name: '节点1',
    children: [
      {
        id: '1-1',
        name: '节点1-1',
        children: [
          {
            id: '1-1-1',
            name: '节点1-1-1'
          }
        ]
      },
      {
        id: '1-2',
        name: '节点1-2'
      }
    ]
  },
  {
    id: '2',
    name: '节点2',
    children: [
      {
        id: '2-1',
        name: '节点2-1'
      }
    ]
  }
]
//递归
function findNode(tree, func) {
  for (const node of tree) {
     if (func(node)) return node
     if (node.children) {
       const res = this.findNode(node.children, func)
       if (res) return res
     }
   }
   return null
 }
 //while
 function findNode(tree, func) {
  let node, list = [...tree]
  while ((node = list.shift())) {
    if (func(node)) {
      return node
    }
    node.children && list.unshift(...node.children)
  }
}
//for
function findNode(tree, func) {
  let node, curTree = [...tree]
  for (let i = 0; i < curTree.length; i++) {
    if (func(curTree[i])) {
      return curTree[i]
    }
    if (curTree[i].children) {
      curTree.splice(i + 1, 0, ...curTree[i].children)
    }
  }
}

使用:

const firstNoChildrenNode = this.findNode(treeData, (node) => {
 return !node.children
})
console.log(firstNoChildrenNode)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值