[英]C Binary Search Tree insertion
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);
}
}
I'm trying to build a binary search tree to process a linked list into an ordered bst. 我正在尝试构建一个二进制搜索树,以将链接列表处理为有序的bst。 I can get the output of root to show up correctly but not anything else.
我可以得到root的输出以正确显示,但没有其他显示。 It spits out some garbage and i'm not sure why.
它吐出一些垃圾,我不确定为什么。 I set up a printf statement and it shows that it is inserting actual strings.
我设置了一个printf语句,它表明它正在插入实际的字符串。 Am i doing something wrong?
难道我做错了什么? This isn't all the code but I think it's enough so people can understand what i'm doing.
这不是全部代码,但我认为足够了,这样人们就可以了解我在做什么。 Suggestions?
有什么建议吗?
return node
; return node
; --> return root;
->
return root;
As per BLUEPIXY's comment, this was the correct answer.– BLUEPIXY 2 mins ago 根据BLUEPIXY的评论,这是正确的答案。– BLUEPIXY 2分钟前
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.