gpt4 book ai didi

C 二叉搜索树插入

转载 作者:行者123 更新时间:2023-11-30 17:24:03 24 4
gpt4 key购买 nike

typedef struct word {
char *str;
int freq;
struct word *right;
struct word *left;
} Word;



Word *root = NULL; //global

while(pCounter != NULL){
if(root == NULL){
Word *x = (Word *)malloc(sizeof(Word));
x->str = (char*)malloc(strlen(pCounter->str)+1);
//printf("%s", node->str);
strcpy(x->str,pCounter->str);
x->freq = pCounter->freq;
x->left = NULL;
x->right = NULL;
root = x;
}
else {
Insert(pCounter, root);
}
pCounter = pCounter ->pNext;
}


void * Insert(Word *node, Word *root)
{
printf("inserted%s\n", node->str);
if(root==NULL)
{
Word *x = (Word *)malloc(sizeof(Word));
x->str = (char*)malloc(strlen(node->str)+1);
//printf("%s", node->str);
strcpy(x->str,node->str);
x->freq = node->freq;
x->left = NULL;
x->right = NULL;
return x;
//node = root;
}
else if (strcmp(node->str, root->str)==0){

root -> freq = root->freq+1;
}
else if (strcmp(node->str, root->str)<1){

root->left = Insert(node,root->left);
}
else {
root->right = Insert(node, root->right);
}

return node;


}

void ordered(Word *n){
//printf("ordered");
if(n != NULL){
ordered(n->left);
printf("%-30s %5d\n", n->str, n->freq);
ordered(n->right);
}
}

我正在尝试构建一个二叉搜索树来将链表处理为有序 bst。我可以让 root 的输出正确显示,但不能显示其他任何内容。它吐出一些垃圾,我不知道为什么。我设置了一个 printf 语句,它显示它正在插入实际的字符串。难道我做错了什么?这不是全部代码,但我认为这已经足够了,这样人们就可以理解我在做什么。有建议吗?

最佳答案

返回节点; --> return root; 根据 BLUEPIXY 的评论,这是正确的答案。– BLUEPIXY 2 分钟前

关于C 二叉搜索树插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27337402/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com