【发布时间】:2021-11-23 05:28:45
【问题描述】:
#include <stdlib.h>
struct btNode
{
int data;
struct btNode *right;
struct btNode *left;
} * root, *temp1, *temp2;
void create(int);
void insert(int);
void postorder(struct btNode *);
int main()
{
int choice, item;
do
{
printf("\nChoose one of the options:\n");
printf("1. Insert 2. Delete 3. Inorder 4. Postorder 5. Preorder 6. Exit\n");
scanf("%d", &choice);
switch (choice)
{
case 1:
printf("\nEnter any number to insert:");
scanf("%d", &item);
insert(item);
break;
case 4:
postorder(root);
break;
case 6:
break;
default:
printf("\nWRONG INPUT");
}
} while (choice != 6);
return 0;
}
void create(int num)
{
temp1 = (struct btNode *)malloc(sizeof(struct btNode));
temp1->data = num;
temp1->left = NULL;
temp1->right = NULL;
}
void insert(int num)
{
create(num);
if (root == NULL)
{
root = temp1;
printf("%d inserted\n", root->data);
}
else
{
temp2 = root;
while (temp2 != NULL)
{
//printf("inside while");
if (temp2->data >= num)
{
temp2 = temp2->left;
}
else
{
temp2 = temp2->right;
}
}
temp2 = temp1;
printf("%d inserted\n", temp2->data);
}
}
void postorder(struct btNode *r)
{
if (root == NULL)
{
printf("Tree is empty");
return;
}
else
{
postorder(r->left);
postorder(r->right);
printf("%d ", r->data);
}
}
以上是一个不完整的 BST 菜单驱动程序。我现在尝试执行创建节点、插入和后序的功能。但是当我插入几个元素并尝试执行后序时,主要的问题就出现了,程序突然杀死了自己。我试图调试程序,在所有三个函数处设置断点。并且在调试create() 和insert() 函数期间运行良好,但主要问题出现在postorder() 函数期间。请帮我解决问题。
【问题讨论】:
-
全局变量是多个问题的根源。我建议摆脱它们。相反,学习如何使用函数返回值以及如何通过引用传递参数。
-
@user3386109,在后序中,我看到的一个明显问题是检查
root == NULL而不是r == NULL。 -
另请注意,您仅将 NULL 分配给 left 和 right,因此任何节点都不能指向任何其他节点。
-
@kiner_shah 是的,我忽略了名称不匹配。
标签: c binary-search-tree