4.3二叉树的遍历王道数据例程实现
#include <stdio.h>
#include <stdlib.h>
typedef int ElemType;
typedef struct BiTNode{
ElemType data
struct BiTNode *lchild,*rchild;
} BiTNode,*BiTree;
void PreOrder(BiTree T){
if(T!=NULL){
int a=T->data;
printf(" %d",a);
PreOrder(T->lchild);
PreOrder(T->rchild);
}
}
void InOrder(BiTree T){
if(T!=NULL){
InOrder(T->lchild);
int a=T->data;
printf(" %d",a);
InOrder(T->rchild);
}
}
void PostOrder(BiTree T){
if(T!=NULL){
PostOrder(T->lchild);
PostOrder(T->rchild);
int a=T->data;
printf(" %d",a);
}
}
BiTree CreateBiTree(BiTree &T){//利用先序遍历创建二叉树
int x; //可输入120460030500 王道书上例程
scanf("%d",&x);
if(x!=0){ //等于0时跳过,所以该节点还为空
T=(BiTree)malloc(sizeof(BiTNode));
T->data=x;
T->lchild=NULL;
T->rchild=NULL;
T->lchild=CreateBiTree(T->lchild);
T->rchild=CreateBiTree(T->rchild);
}
return T;
}
int main()
{
BiTree T;
CreateBiTree(T);
printf("前序遍历结果\n");
PreOrder(T);
printf("\n中序遍历结果\n");
InOrder(T);
printf("\n后序遍历结果\n");
PostOrder(T);
system("pause");
}