#include "stdio.h"
#include "stdlib.h"
#define ERROR 0
#define OK 1
typedef char TElemType;
typedef int Status;
typedef struct BinaryTree
{
TElemType data; /*结点数据域*/
struct BinaryTree *lchild; /*左孩子指针 */
struct BinaryTree *rchild; /*右孩子指针*/
}*BiTree,BiNode;
Status CreateBiTree(BiTree *T)
{ /* 按先序次序输入二叉树中结点值(一个字符),’#’字符表示空树。构造二叉链表表示的二叉树 T*/
char ch;
scanf ("%c",&ch ); /* 输入字符*/
if(ch=='#') /* 若是#字符,则令指针为空*/
(*T)=NULL;
else {
if ( ! ( (*T) = ( BiNode * ) malloc ( sizeof ( BiNode ) ) ) )
return ERROR;
(*T)->data=ch; /* 生成根结点*/
CreateBiTree ((& (*T)->lchild) ); /*构造左子树*/
CreateBiTree ((&(* T)->rchild )); /*构造右子树 */
}
return OK;
}
Status printelem(TElemType d)
{
printf("%c\t",d);
return OK;
}
Status PreOrderTraverse(BiTree T,Status (*Visit)(TElemType d))
{ 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 d))
{ 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 d))
{ if(T) {
if(PostOrderTraverse(T->lchild,Visit)) /*遍历左子树*/
if(PostOrderTraverse(T->rchild,Visit)) /*遍历右子树*/
if(Visit(T->data)) /*访问根结点*/
return OK;
return ERROR;
} else
return OK;
}
void main()
{
BiTree root;
printf("er cha shu de sheng cheng he bian li .c\n");
printf("=======================================\n\n\n\n\n");
printf("qing shu ru zi fu:\n\n");
CreateBiTree(&root);
printf("\nxian xu bian li :\n");
PreOrderTraverse(root,printelem);
printf("\nzhong xu bian li :\n");
InOrderTraverse(root,printelem);
printf("\nhou xu bian li :\n");
PostOrderTraverse(root,printelem);
getch();
}