using a binary search tree I need to add to a vector all int elements of the heaviest path of the tree.
for example I have 20,7,6,9,11,21
the values that should be added to the vector would be 20 ,7,9,11
I have written the implementation of the calculation of the heaviest path, but I don’t know how to change it so the right elements will be added to the vector:
int Tree::maxBranch(Node* node){
if(node==NULL)
return 0;
int leftSum=node->data+maxBranch(node->left);
int rightSum=node->data+maxBranch(node->right);
if(rightSum>leftSum){
return rightSum;
}
return leftSum;
}
Your code as written does not keep track of the branches it’s followed at all – it only gets the sum.
You should change the function to take an
std::vector<int>&as an argument (note the&, for a reference type, since you need to effectively return two values).Call it with an empty vector.
Before the line where you do the recursive call on
node->left, you should save the original vector as, for instance,std::vector<int> vec_left(input_vector)andstd::vector<int> vec_right(input_vector). Then pass the two copies down to the recursive calls.Now, in the code, just before
return rightSum, you should have avec_right.push_back(node->id); input_vector = vec_right;. Just beforereturn leftSum, you should likewise have avec_left.push_back(node->id); input_vector = vec_left;. In English, you keep the path that was made by the branch which had the highest sum, and discard the other one.