我编写了一个程序,该程序创建一个二叉搜索树,在其中动态插入字符串并按顺序显示bst。问题是,当我在二进制搜索树中插入字符串以查看它是否起作用时,是因为它的运行方式就像我在树中确实插入了某些东西一样,但是我并没有真正做到这一点,所以每次尝试显示它时都会告诉我,树是空的,我真的不知道问题出在哪里。
也许create function是错误的,但我不这样认为,它似乎并没有在结构中真正插入任何字符串。
也许create function是错误的,但我不这样认为,它似乎并没有在结构中真正插入任何字符串。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <limits.h>
typedef struct bst{
char *info;
struct bst *sx;
struct bst *dx;
}bst;
bst* root = NULL;
bst* temp = NULL;
bst* insert(bst*,char *);
bst* create(char *);
void inorder(bst *);
void main()
{
int select;
int count=0;
printf("\nSelect one of these options:\n");
printf("[1] insert a string\n");
printf("[2] display inorder\n");
printf("[3] exit\n");
while(1){
printf("\nEnter your choice : ");
scanf("%d", &select);
switch (select){
case 1: ;
char *key;
printf("\ninsert string: ");
scanf("%s",key);
insert(root,key);
count++;
printf("There are %d nodes\n",count);
break;
case 2:
inorder(root);
break;
case 3:
exit(0);
break;
default :
printf("Wrong");
break;
}
}
}
bst* insert(bst* t,char* value){
if(t==NULL)
t=create(value);
else if(t!=NULL){
if(strcmp(value,t->info)<0)
t->sx=insert(t->sx,value);
else if(strcmp(value,t->info)>0)
t->dx=insert(t->dx,value);
}
return t;
}
bst* create(char *data){
temp=malloc(sizeof(struct bst));
temp->info=malloc((strlen(data)+1)*sizeof(char));
strcpy(temp->info,data);
temp->sx = temp->dx = NULL;
return temp;
}
void inorder(bst *t){
if (root == NULL){
printf("No elements in a tree to display");
return;
}
if (t->sx != NULL)
inorder(t->sx);
printf("%s -> ", t->info);
if (t->dx != NULL)
inorder(t->dx);
}
有人知道如何解决吗?
最佳答案
您永远不会设置root
的值(除NULL外),因此您所做的任何事情都不会被保存。您可以使用“按引用传递”(即传递root
的地址,以便您可以实际更改它),也可以仅依靠root
是全局的事实并直接对其进行修改。
关于c - 在C中以递归方式插入并显示BST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49785864/