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)