function listToTree(list) {
let map = {}
let node
let roots = []
for (let i = 0; i < list.length; i++) {
list[i]._level = 1
map[list[i].id] = i // initialize the map
list[i].children = [] // initialize the children
}
for (let i = 0; i < list.length; i++) {
node = list[i]
if (!!node.parentId && node.parentId != '0') {
node._level = list[map[node.parentId]]._level + 1
list[map[node.parentId]].children.push(node)
} else {
roots.push(node)
}
}
return roots
}
如上为JavaScript,该算法比递归效率更高,支持无限层级,可以在浏览器中debug看一下过程。