我尝试通过C编程实现二叉搜索树。我只写了两个函数。程序编译完美。但是当它运行时,它会要求用户“输入要插入的数据”。数据插入后程序停止。
#include<stdio.h>
#include<stdlib.h>
typedef struct Node
{
int info;
struct Node *left;
struct Node *right;
}node;
node* insert(node *root, int data);
void inorder(node* root);
int main()
{
int data,choice;
node *root;
printf("----------------MENU---------------\n");
printf("1. Insert\n");
printf("2.Inorder traversal\n");
printf("3.Exit\n");
while(1)
{
printf("Enter your choice: ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("Enter the data to be inserted: ");
scanf("%d",&data);
root=insert(root,data);
break;
case 2:inorder(root);
break;
case 3:
exit(0);
}
}
return 0;
}
node* insert(node *root, int data)
{
if(root==NULL)
{
root=(node *)malloc(sizeof(node));
root->info=data;
root->left=root->right=NULL;
return root;
}
else if(data<=root->info)
{
root->left=insert(root->left,data);
return root;
}
else if(data>=root->info)
{
root->right=insert(root->right,data);
return root;
}
}
void inorder(node* root)
{
if(root==NULL)
return;
else
{
inorder(root->left);
printf("%d",root->info);
inorder(root->right);
}
}
最佳答案
诊断
您没有初始化root
(所以它不是可靠的 NULL);你将它传递给insert()
; insert()
使用它,事情就会变得困惑。
node *root = 0; // Or NULL
完成此更改后,代码将运行。打印的数字之间没有留空格,有点难看,但功能似乎还可以。不久之后您将需要编写代码来释放分配的树。
<小时/>评论
我观察到,当我使用我使用的默认选项(在使用 GCC 6.3.0 运行 macOS Sierra 10.12.3 的 Mac 上)编译代码时,我收到了有关此问题的警告。我将您的代码保存到 ub37.c
:
$ gcc -O3 -g -std=c11 -Wall -Wextra -Werror -Wmissing-prototypes \
> -Wstrict-prototypes -Wold-style-definition -c ub37.c
ub37.c:16:5: error: function declaration isn’t a prototype [-Werror=strict-prototypes]
int main()
^~~~
ub37.c: In function ‘main’:
ub37.c:16:5: error: old-style function definition [-Werror=old-style-definition]
ub37.c: In function ‘insert’:
ub37.c:63:1: error: control reaches end of non-void function [-Werror=return-type]
}
^
ub37.c: In function ‘main’:
ub37.c:33:17: error: ‘root’ may be used uninitialized in this function [-Werror=maybe-uninitialized]
root=insert(root,data);
~~~~^~~~~~~~~~~~~~~~~~
cc1: all warnings being treated as errors
$
“严格原型(prototype)”和“旧样式定义”警告可通过写入 int main(void)
解决。这并不是一个世界末日的问题,但它很容易解决。
“控制到达非空函数末尾”可以通过替换最后的 else if
来解决只需 else
在insert()
。我观察到 >=
的相等部分已被之前的else if (data <= root->info)
覆盖也测试一下。在某种程度上,这并不重要——您已经涵盖了所有情况。在另一个层面上,它很容易修复,并且修复后的代码可以执行您想要的操作,因此它应该被修复。
主要错误由“root
”标识。可能会使用未初始化的错误。
因为我用 -Werror
编译同样,任何一个警告都会阻止代码编译。
确保您使用类似严格的警告选项进行编译。它使您的代码变得更好。
关于c - C 中的二叉搜索树。程序无法正常工作。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42652032/