1

我在添加到二叉搜索树时遇到问题,我的程序似乎正在添加到临时结构中。我认为为了使其正常工作,我必须在将变量节点设置为结构的一部分之前为左右节点调用 malloc。我只是不确定在代码中的哪个位置使用 malloc,所以它的其余部分仍然有效 =/

 typedef struct BiTree_ {
   BiTreeNode *root;
   int size;
} BiTree;

    typedef struct BitTreeData_ {
   char *str;
   int diff;
   int start_count;
   int end_count;
   int hidden;
} BiTreeData;

 typedef struct BiTreeNode_ {
    BiTreeData *data;
    struct BiTreeNode_ *right;
    struct BiTreeNode_ *left;
} BiTreeNode;

    int
bitree_insert(BiTree *tree, BiTreeNode *node, char *str)
{
    if(tree->root == NULL){
        tree->root = (BiTreeNode*)malloc(sizeof(BiTreeNode*));
        tree->root->data = (BiTreeData*)malloc(sizeof(BiTreeData*));
        tree->root->right = NULL;
        tree->root->left = NULL;
        tree->root->data->str = str;
        tree->root->data->hidden = 0;
        tree->root->data->start_count = 0;
        tree->root->data->end_count = 0;
        tree->root->data->diff = 0;
        tree->size++;
        return 0;
    }    
    if(node == NULL){
        node = (BiTreeNode*)malloc(sizeof(BiTreeNode));
        node->right = (BiTreeNode*)malloc(sizeof(BiTreeNode*));
        node->right = NULL;
        node->left = (BiTreeNode*)malloc(sizeof(BiTreeNode*));
        node->left = NULL;
        node->data = (BiTreeData*)malloc(sizeof(BiTreeData*));
        node->data->str = str;
        node->data->hidden = 0;
        node->data->start_count = 0;
        node->data->end_count = 0;
        node->data->diff = 0;
        tree->size++;
        return 0;
    }
    if(strcmp(str, node->data->str)<0){
        if(node->left == NULL){

            return 0;
        }
                bitree_insert(tree, node->left, str);
    }
    if(strcmp(str, node->data->str)>0){
        if(node->right == NULL){
            return 0;
        }
        bitree_insert(tree, node->right, str);
    }    
    return 0;
} 
4

1 回答 1

1

您传递给函数的参数bitree_insert是按值传递的,而不是按引用传递的。因此,例如,node是指向BitTreeNode类型变量的指针。如果然后分配给node,它会设置名为 node 的局部变量的值。看来您想要做的是传递对节点的引用,即BitTreeNode **. 这样,当您分配给*node该分配时,是从调用者传递的指针而不是局部变量。

于 2012-10-27T17:20:26.930 回答