How does the json tree count the number of descendant nodes of all nodes?

const Tree = [{
    name:1,
    children:[{}],
    childrenNum:0
}]

calculate the number of his descendants for each node childrenNum
did not write it for a long time and ask the boss for guidance

Apr.06,2022

the structure of each is the same?

Recursion is fine if it is consistent.

function cal(tree) {
    const childNum = tree.children.reduce((result, childTree) => {
        return cal(childTree) + result
    }, tree.children.length)
    tree.childrenNum = childNum
    return childNum
}

// 

tree.forEach(t => cal(t))
Menu