父节点值是其所有子节点的总和

parent nodes value to be the sum of all its childrens

我有一个不是二叉树的编辑树(可以更改节点的值),我想将节点值的总和存储在父节点中。 即:

   50
/   |   \
10  25  15
|   | \   |  \
10  3 22  10  5

在编辑中我成功更改了所有层级,但初始化我没有成功,例如我只有最深层次的值(10 3 22 10 5),然后想从它。

尝试使用子节点值更新父节点值,例如

Node node = //get the changed node
while (node.Parent != null)
{
    node = node.Parent;
    // set node.Value from sum of node.childnode values 
} 

我的策略是进行自上而下的遍历。叶节点只是 return 它们的当前值。内部节点根据其子节点的总和重新计算。

function initialize(node) {
    // internal nodes get their total from children
    if (node.children.length > 0) {
        node.value = 0;
        for (var i = 0; i < node.children.length; i++) {
            node.value += initialize(node.children[i]);
        }
    }
    return node.value;
}
initialize(root);