function arrayToTree(array) {
const root = array[0]
array.shift()
const tree = {
id: root.id,
val: root.val,
children: array.length > 0 ? toTree(root.id, array) : []
}
return tree
}
function toTree(parenId, array) {
const children = []
const len = array.length
for (let i = 0; i < len; i++) {
const node = array[i]
if (node.parentId === parenId) {
children.push({
id: node.id,
val: node.val,
children: toTree(node.id, array)
})
}
}
return children
}
02-18
3593