This is a problem in my research code and I am wondering what is the efficient way to go about doing this. I am leaving out unnecessary details and I am presenting it in a manner so that the crux of the problem can be understood.
Lets say I have a binary tree with numbers on each node. I want to find the minimum sum of all the branches in the tree starting from root to leaf. Below is a very rough pseudocode.
int minimum(tree){
// Some base cases
left_min = minimum(tree->left);
right_min= minimum(tree->right);
if (left_min < right_min){
return current_value + left_min;
}
else{
return current_value + right_min;
}
}
From this, I can compute the minimum. However, if I want to compute the nodes which give me the minimum, how would I go about? i.e. if the answer is say 14, I want to find out which nodes at each level in the tree add up to give me a sum of 14. What would be the efficient way to go about doing this with minimal change to the existing function? By minimal change, I mean I can add additional variables to keep track of the branch but not rewrite the function completely.
Thanks
You can use a list or stack or queue instead of vector: