Kyuu
Kyuu

Reputation: 1045

adding integers from each node of a tree

How would I be able to add data from different nodes together? Inserttotree() just creates a new node and enters the data value specified.

So basically I'm just trying to add 2 and 3 together in the countquantity() function.

typedef struct tree_s tree_t;
typedef int data_t;

struct tree_s {
    data_t data;
    tree_t *left;
    tree_t *right;
};

int main(int argc, char **argv){
    tree_t *tree;
    tree = NULL;
    tree = insertToTree(tree, 3);
    tree = insertToTree(tree, 2);
    printf("Total: %d\n", countQuantity(tree));
    return 0;
}

int countQuanity(tree_t *tree){
    int i = 0;
    if(tree == NULL){
        return i;
    }

    i = tree->data + countQuantity(tree->left);
    i = tree->data + countQuantity(tree->right);
    return i;
}

Upvotes: 1

Views: 48

Answers (2)

Eugene Sh.
Eugene Sh.

Reputation: 18341

The result is a sum of the node's value and the computed values of both subtrees:

i=tree->data + countQuantity(tree->left) + countQuantity(tree->right)

Upvotes: 2

Ghazanfar
Ghazanfar

Reputation: 1469

Look this part of your code,

i = tree->data + countQuantity(tree->left);
i = tree->data + countQuantity(tree->right); 
    //The value of i is being over written here
return i;

Your code should have been more like this,

i = tree->data + countQuantity(tree->left);
i += countQuantity(tree->right);
return i;

Upvotes: 1

Related Questions