【发布时间】:2020-10-15 14:35:25
【问题描述】:
我尝试用 C 语言编写一个树程序,从插入函数开始,如下所示:
void insert(int val)
{
struct node * nn = (struct node *)malloc(sizeof(struct node));
nn->data = val;
nn->left = NULL;
nn->right = NULL;
if(root == NULL)
{
root = nn;
}
else
{
struct node *ptr = root;
while(ptr->left != NULL && ptr->right != NULL)
{
if(nn->data < ptr->data)
{
ptr = ptr->left;
}
else
{
ptr = ptr->right;
}
}
if(ptr->data < nn->data)
{
ptr->right = nn;
}
else
{
ptr->left = nn;
}
}
然后我编写了代码来显示这样形成的树的节点:
void display()
{
struct node *n;
if(root == NULL)
{
printf("Tree is Empty\n");
}
else
{
n = root;
if(n!=NULL)
{
printf("%d",n->data);
display(n->left);
display(n->right);
}
}
}
这是主要功能:
int main()
{
int ch,val;
while(ch!=3)
{
printf("1. Insert\n2. Display\n3. Exit\nEnter your choice: ");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("Enter value to be inserted: ");
scanf("%d",&val);
insert(val);
break;
case 2:
display();
break;
case 3:
ch=3;
printf("Exiting....\n");
break;
default:
printf("Invalid choice, please try again\n");
break;
}
}
return 0;
}
但是当我在插入几个节点后尝试执行显示函数时,它只打印了无限循环中的第一个节点。
有人可以帮我解决这个问题吗?
【问题讨论】:
-
display(n->left);但display不需要任何参数。你的意思是void display(struct node *root) { ... }? -
阅读您的 C 编译器(例如 GCC...)和调试器(例如 GDB)的文档。另请阅读 Modern C 和 Introduction to Algorithms
-
请发布一个有效的 MCVE minimal reproducible example 以反映您正在运行的代码,否则我们将陷入无限无意义的错误追逐 - 即您将内容传递给
display(...)而在此代码中不需要参数。 -
这是开始学习如何使用调试器的绝佳机会。使用调试器进行编程比没有调试器要容易得多。