I want to calculate the sum of the child nodes and save that on parent node. As showed in image blue numbers are sum of children.
I have tried this so far:
const tree = {
name:"Root Node",
value:0,
sumOfTheChildren:0,
children: [
{
name:"A Node",
value:10,
sumOfTheChildren:0,
children:[]
},
{
name:"B Node",
value:10,
sumOfTheChildren:0,
children:[]
}
]
}
and so on ....
So in sumOfTheChildren of every node i want calculate sum of the children (all descendant nodes)
so i am trying to do post-order tree traversal like this.
let sum = 0;
function postOrder(root) {
if (root == null) return;
root.children.forEach((el) =>{
postOrder(el);
});
sum+=root.value;
// Here i am not sure how to do this
root.sumOfTheChildren+=root.value;
}
postOrder(tree);
But this is not giving required result. So How do i get proper sum?
