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))
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b3bb86-2c2c2.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b3bb86-2c2c2.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?