我在添加到二叉搜索树时遇到问题,我的程序似乎正在添加到临时结构中。我认为为了使其正常工作,我必须在将变量节点设置为结构的一部分之前为左右节点调用 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;
}