我试图通过调用TREEinsert函数frim主函数插入一个数字列表到二进制搜索树,但是每当我的程序运行它不打印任何数字插入二进制搜索树。我已经完成了TREEinsert函数和Displayinorder函数,但似乎无法发现任何函数的功能问题。我对二叉搜索树有一个基本的了解,并且看过很多例子,试图了解BST的工作。任何指导都将非常有帮助。如何在C中的二进制搜索树中插入数字?
struct node
{
int info;
struct node *left;
struct node *right;
};
void TREEclear(struct node* t)
{
t = NULL;
}
void TREEinsert(struct node* t, int x)
{
//insert in BST
if(t == NULL)
{
t = (struct node*)malloc(sizeof(struct node));
t->info = x;
t->left = NULL;
t->right = NULL;
}
else
{
if (x < t->info)
TREEinsert(t->left, x);
if (x > t->info)
TREEinsert(t->right, x);
}
}
void Displayinorder(struct node* t)
{
//in order: (LC)(P)(RC)
if (t != NULL)
{
Displayinorder(t->left); //LC
printf("%d\t", t->info); //P
Displayinorder(t->right); //RC
}
}
struct node *root;
int main()
{
TREEclear(root);
TREEinsert(root, 5);
TREEinsert(root, 8);
TREEinsert(root, 2);
TREEinsert(root, 6);
Displayinorder(root);
printf("\n\n");
system("PAUSE");
return 0;
}
't'是'TREEinsert'中的局部变量。您对此所作的任何更改都不会在调用函数中得到体现。您应该将根指针的地址作为'struct node ** p'传递。 –
请正确格式化您的代码。 –