c - 在C中以递归方式插入并显示BST

标签 c

我编写了一个程序,该程序创建一个二叉搜索树,在其中动态插入字符串并按顺序显示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/

相关文章:

java - java中如何保存从jni返回的void*以供以后使用

在 C 中的字符串 vector 之间复制字符串

c++ - 如何在C/C++中获取HTML

c - 逐行读取文件并将其存储到数组中不起作用

c - 返回空结构而不是 NULL 的奇怪问题

C 原型(prototype)函数

c - 如果数组中的每个整数都不同,我该如何编写一个返回 true 的函数?

在雪豹中创建缓冲区溢出

c - Ex 1-17 无限循环

c - 将所有文件内容读入字符串 - 将 off_t 的值传递给 malloc() (其中需要 size_t)是否会遇到问题?