Finding sum recursively in a tree

I have a *kids, *sibling tree structure for the following input.

BIKE(2*AXLE, AXLE(X[50.], Y), Y[10.])

As you see, the price may not be given at times. If that is the case, you have to calculate the price for that particular part somewhere else in the tree.

This is the funtion I’ve written

double calculate_price(node *n){
    node *temp;
    if(n == NULL){
        return 0;
    }else if(n->information->dtype == BASIC){ /////////BASIC MEANS GIVEN WITH BRACKETS, E.G X[50.], Y[10.]
        return (n->information->quantity) * (n->information->price) + calculate_price(n->sibling);
    }else if(!identify_unknown(n)){ //////FOR PARTS WITH KIDS e.g AXLE(X[50.], Y)
        return n->information->quantity*((calculate_price(n->firstkid))) + ((calculate_price(n->sibling)));
    }else{////////THIS HERE IS PROBLEMATIC
        temp = search(root, n->information->name);
        temp->sibling = NULL;
        return n->information->quantity * calculate_price(temp)/ temp->information->quantity + calculate_price(n->firstkid) + calculate_price(n->sibling);
    }
}

In the else block of the code above, I tried to find the price for the parts not having sufficient information. 2*AXLE, and Y in AXLE(X[50.], Y) are examples to this situation. My search function searchs the name of the part in the whole tree, and returns a node if it finds the same name with sufficient information elsewhere in the tree. So for example, search returns AXLE(X[50.], Y) for 2*AXLE, and Y[10.] for Y.

In the second line of the else block, I had to set temp->sibling to NULL in order not to have extra calculations. But I think this is problematic since it deletes nodes as a side effect. What I wanted to do was simply

  1. Block temp->sibling and call calculate_price for temp
  2. Once that is done, unblock temp->sibling and continue the calculation for node n

But It seems I couldn’t handle it. For the input I have given at the top, I get 150.000000 as a result whereas the correct result is 190.000000. It appears Y isn’t involved in calculations.(probably because it was set to NULL at some part)

Should I have a helper function to do this, or can I modify the code and get the results?


Source: c#

Leave a Reply