private void sumNode(TNode node) {
int sum = 0;
if (node == null)
return;
sumNode(node.getLeft());
sumNode(node.getRight());
if (node.getLeft() != null && node.getRight() != null) {
sum = (node.getData() + node.getLeft().getData() + node.getRight()
.getData());
} else if (node.getLeft() != null) {
sum = (node.getData() + (Integer) node.getLeft().getData());
} else if (node.getRight() != null) {
sum = (node.getData() + node.getRight().getData());
} else {
sum = 0;
}
node.setData(sum);
}
I know my method is totally wrong – I have no idea how to do this.
I want to replace each node value to be the summation of all its descendants, can anyone guide me how to do?
I have ran out ideas for how to solve this problem. Even pseudocode will be appreciated.
The problem is:
- My tree has:
5 2 1 3 6 8 - The outcome is:
0 0 2 0 6 13, - The expected outcome is:
0 0 4 0 8 20
If you want to include the original value of the node in the sum, then this is very easy with recursion:
If you do not want to include the original value, then a single recursive pass is not enough because by the time you calculate the value of a non-leaf node N with two leaves L1 and L2, the values in L1 and L2 have already been updated to zeros, so you cannot use the original values of L1 and L2 to store N. If you are allowed to add a new
originalItementry in the node, you can store the original value there, use my solution above and then run a final pass which subtracts the value oforiginalItemfromitemfor every node in the tree: