凌乱了,求救,二叉树的创建和中序遍历
#include<stdio.h>二叉树 遍历
#include<string.h>
#include<stdlib.h>
typedef struct NODE
{
int data;
NODE* lchild;
NODE* rchild;
}NODE,*tree;
void creat(tree t)
{
int x;
scanf("%d",&x);
if(x==-1)
t=NULL;
else
{
t=(tree)malloc(sizeof(NODE));
t->data=x;
creat(t->lchild);
creat(t->rchild);
}
}
void mid(tree t)
{
if(t)
{
mid(t->lchild);
printf("%d ",t->data);
mid(t->rchild);
}
}
int main()
{
tree t;
creat (t);
mid(t);
return 0;
}
struct tree
{
int data;
struct tree *lchild;
struct tree *rchild;
};
// 先序建立二叉树
struct tree *create(struct tree *BT,int k)
{
struct tree *p;
int x;
p=(struct tree *)malloc(sizeof(struct tree));
printf("输入结点的整数值(0表示空) : ");
scanf("%d",&x);
if(x!=0)
{
if(!(p=(struct tree *)malloc(sizeof(struct tree))))
exit(0);
//生成主根或子树根
p->data=x;
p->lchild=NULL;
p->rchild=NULL;
if(k==0)
BT=p;
if(k==1)
BT->lchild=p;
if(k==2)
BT->rchild=p;
create(p,1);//建立左子树
create(p,2);//建立右子树
}
return(BT);
}
// 先序遍历
int visit(struct tree *BT)
{
if(BT!=NULL)
{
printf("%d ",BT->data);
visit(BT->lchild);
visit(BT->rchild);
}
return 0;
}
void main()
{
struct tree *p;
p=(struct tree *)malloc(sizeof(struct tree));
p=create(p,0);
visit(p);
printf("\n");
}