I would like to know the algorithm for the following problem:
"Given a BST(There can be duplicate nodes), replace every node with value which is sum of values of all nodes greater than equal to the current node."
Example:
5 15 2 10 o/p: 17 10
I did it with reverse in-order traversal keeping a variable 'sum'. Here is the code:
public static void replaceNodeValue(BSTNode root, int[] sum) {
if (root == null) return;
replaceNodeValue(root.right, sum);
root.data = (sum[0] = sum[0] + root.data);
replaceNodeValue(root.left, sum);
}
The problem is this code works only if the tree doesn't contain a duplicate node. I am looking for the correct algorithm which will handle duplicate nodes also.
One case for which the code will fail is:
5 5 5
Please help. Thanks