#include<stdio.h> #include<stdlib.h> typedef char ElemType; //结点定义 typedef struct node{ ElemType data; struct node* lchild,*rchild; }BiTNode,*BiTree; //初始化一个空的二叉树 void InitBiTree(BiTree &tree) { // tree存储NULL,表示没有二叉树 tree=NULL; } //创建二叉树 #表示空结点 void CreateBitree(BiTree &T) { char ch; if((ch=getchar())=='#') T=NULL; else { T=(BiTNode*)malloc(sizeof(BiTNode)); T->data=ch; CreateBitree(T->lchild); CreateBitree(T->rchild); } } //先序遍历二叉树 void preOrder(BiTree &tree) { if(tree!=NULL) { printf("%c",tree->data); preOrder(tree->lchild); preOrder(tree->rchild); } } //中序遍历二叉树 void InOrder(BiTree &tree) { if(tree!=NULL) { InOrder(tree->lchild); //一直访问到最左边的叶子节点 printf("%c",tree->data); InOrder(tree->rchild); } } //后序遍历 void PostOrder(BiTree &tree) { if (tree!=NULL) { PostOrder(tree->lchild); PostOrder(tree->rchild); printf("%c",tree->data); } } int main() { BiTree tree; InitBiTree(tree); CreateBitree(tree); printf("先序遍历:"); preOrder(tree); printf("\n"); printf("中序遍历:"); InOrder(tree); printf("\n"); printf("后序遍历:"); PostOrder(tree); return 0; }