从树的每个节点添加整数

时间:2015-05-19 16:20:40

标签: c recursion struct tree

我如何能够将来自不同节点的数据一起添加? Inserttotree()只需创建一个新节点并输入指定的data值。

所以基本上我只是想在2函数中添加3countquantity()

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;
}

2 个答案:

答案 0 :(得分:2)

结果是节点值与两个子树的计算值的总和:

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

答案 1 :(得分:1)

查看代码的这一部分,

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

您的代码应该更像这样,

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