# Adding node values of binary tree

• 01-15-2012
lios1984
Adding node values of binary tree
Hello to everyone..

I have made a function in order to add the values of the nodes on each path of the tree. For example if I enter numbers 7, 8, 9, 4, 1 then for the path (7>4>1) the cost must be 7+4+1=12.
The maximum cost is wanted.

I give you the code of the function. I have a problem because despite the fact it adds correctly for the traversal to the left, it doesn't seem to "remember" correctly the maxCost value when changing traversal. In addition, it seems to return in the end the root value as maxCost.

Could you help me??

Code:

```int findcosthelp (node n, int cost, int maxCost) {         if (n != NULL) {         cost=cost + n->key;         printf("%d %d ", cost, maxCost);         if (cost > maxCost)         maxCost = cost;         findcosthelp(n->left, cost, maxCost);         findcosthelp(n->right, cost, maxCost);        }     return cost; } int findcost (node n, int cost, int maxCost) {     cost=0;     maxcost=0;     findcosthelp(n, cost, maxcost);    }```
• 01-15-2012
lios1984
Anyone??
• 01-15-2012
iMalc
Well, you code does nothing to get the maxCost out of either function.
You don't actually need to pass in cost or maxCost either.

Just perform the recursive calls to get the subtree costs, then return the cost of the current node plus the larger from each subtree. The only parameters the function needs is the node, and you only need one function, not two.
• 01-15-2012
lios1984
What do you mean "plus the larger from each subtree"?
• 01-16-2012
iMalc
Okay so you know how to call this function right?
Assuming you eliminate the parameters that should not be there then that looks like this:
Code:

```int cost; cost = findcost(n);```
Well, to find the larger subtree cost, you call findcost once with n->left and then again with n->right (the two subtrees). This will give you two possible values. All you need to do then is return whichever of those numbers is greater.