遍历二叉树(递归)
#include<stdio.h>
#include<stdlib.h>
#define OK 1;
#define ERROR 0;
typedef char TElemType;
typedef int Status;
typedef struct BiTNode{
TElemType data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
Status CreateBiTree(BiTree &T){
char ch;
scanf("%c",&ch);
if(ch=='#'){
T=NULL;
}else{
T = (BiTree )malloc (sizeof(struct BiTNode ));
T->data = ch;
CreateBiTree (T->lchild );
CreateBiTree (T->rchild );
}
return OK;
}
Status PreOrderTraverse(BiTree T,Status (*Visit)(TElemType e)){
if(T){
if(Visit (T->data ))
if(PreOrderTraverse (T->lchild ,Visit ))
if(PreOrderTraverse (T->rchild ,Visit ))
return OK;
return ERROR;
}else
return OK;
}
Status InOrderTraverse(BiTree T,Status (*visit)(TElemType e)){
if(T){
if(InOrderTraverse (T->lchild ,visit ))
if(visit (T->data ))
if(InOrderTraverse(T->rchild ,visit ))
return OK;
return ERROR;
}else
return OK;
}
Status PostOrderTraverse(BiTree T,Status (*Visit)(TElemType e)){
if(T){
if(PostOrderTraverse (T->lchild ,Visit))
if(PostOrderTraverse (T->rchild ,Visit))
if(Visit (T->data))
return OK;
return ERROR;
}else
return OK;
}
Status Visit(TElemType e){
printf("%c",e);
return OK;
}
Status main(){
BiTree T;
CreateBiTree (T);
printf("\n先序遍历二叉树\n");
PreOrderTraverse (T,Visit);
printf("\n中序遍历二叉树\n");
InOrderTraverse(T,Visit);
printf("\n后序遍历二叉树\n");
PostOrderTraverse(T,Visit);
printf("\n");
return OK;
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/a314f736f8860f8f12acbdc0e4fd3358.png)