二叉树先序遍历代码,为什么我只能输出一个地址?却不能输出正确答案??各位大神!
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct stu
{
struct stu *left;
struct stu *right;
int data;
}BiTreeNode,*BiTree;
/****************创建并遍历***************************/
void creat_node(BiTree new1)
{
int c;
scanf("%d",&c);
if(c==0)
new1=NULL;
else
{
new1=(BiTree)malloc(sizeof(BiTree));
new1->data=c;
creat_node(new1->left);
creat_node(new1->right);
}
}
void preOrder1(struct stu *root) //递归前序遍历
{
if(root)
{
printf("%d ",root->data);
preOrder1(root->left);
preOrder1(root->right);
}
}
int main()
{
BiTree root;
creat_node(root);
preOrder1(root);
return 0;
}
c语言一个常识,它的参数是不能在子程序中改变的(你不要以为是指针就会变,指针本身不会变的,变的是它指向的内容)
所以,你的 creat_node(root);不会改变root本身的内容,你的程序能运行只是幸运,因为root若是指向不可读写的部分,程序就直接奔溃了
正确的改
void creat_node(BiTree *new1)
{
int c;
scanf("%d",&c);
if(c==0)
*new1=NULL;
else
{
*new1=(BiTree)malloc(sizeof(BiTree));
(*new1)->data=c;
creat_node(&((*new1)->left));
creat_node(&((*new1)->right));
}
}
然后调用时
creat_node(&root);
//若是C++可用引用,要简单很多
程序测试结果