手打二叉樹的輸入和三序遍歷
#include
#include
struct Node
{
char a ;
struct Node *lchil;
struct Node *rchil;
};
struct Node* Create()//遞歸建樹
{
struct Node *p1;
int x;
p1=(struct Node*)malloc(sizeof(struct Node));
printf("請輸入各個節點以先序遍歷輸入");
scanf("%d",&x);
if(x==0)
{
p1=NULL;
}
else
{
p1=(struct Node*)malloc(sizeof(struct Node));
p1->a=x;
p1->lchirl=Create();
p1->rchirl=Create();
}
return p1;
}
void Fist(struct Node * root)//前序遍歷
{
if(root)
{
printf("%d",root->a);
Fist(root->lchirl);
Fist(root->rchirl);
}
}
void Mid(struct Node * root)//中序遍歷
{
if(root)
{
Mid(root->lchirl);
printf("%d",root->a);
Mid(root->rchirl);
}
}
void Back(struct Node * root)//後續遍歷
{
if(root)
{
Back(root->lchirl);
Back(root->rchirl);
printf("%d",root->a);
}
}
int main()
{
struct Node * root;
root=Create();
printf("樹的前序遍歷\n");
Fist(root);
printf("\n");
printf("樹的中序遍歷\n");
Mid(root);
printf("\n");
printf("樹的後序遍歷\n");
Back(root);
return 0;
}
輸出結果