#include<stdio.h> #include<malloc.h> struct BTNode{ char data; struct BTNode *pLchild; struct BTNode *pRchild; }; struct BTNode * CreateBTree(); void PreTraverse(struct BTNode * pT); void CenterTraverse(struct BTNode * pT); void LastTraverse(struct BTNode * pT); int main(void){ struct BTNode *pT = CreateBTree(); PreTraverse(pT); //先序 CenterTraverse(pT); //中序 LastTraverse(pT); //后序 return 0; } //前序遍历 先根 再左 再右 void PreTraverse(struct BTNode * pT){ if(pT!=NULL){ printf("%c\n",pT->data); if(pT->pLchild!=NULL){ PreTraverse(pT->pLchild); } if(pT->pRchild!=NULL){ PreTraverse(pT->pRchild); } } } //中序遍历 先左 再根 再右 void CenterTraverse(struct BTNode * pT){ if(pT!=NULL){ if(pT->pLchild!=NULL){ CenterTraverse(pT->pLchild); } printf("%c\n",pT->data); if(pT->pRchild!=NULL){ CenterTraverse(pT->pRchild); } } } //后序遍历 先左 再右 再根 void LastTraverse(struct BTNode * pT){ if(pT!=NULL){ if(pT->pLchild!=NULL){ LastTraverse(pT->pLchild); } if(pT->pRchild!=NULL){ LastTraverse(pT->pRchild); } printf("%c\n",pT->data); } } //创建一颗链式树 struct BTNode * CreateBTree(void){ struct BTNode *pA = (struct BTNode *)malloc(sizeof(struct BTNode)); struct BTNode *pB = (struct BTNode *)malloc(sizeof(struct BTNode)); struct BTNode *pC = (struct BTNode *)malloc(sizeof(struct BTNode)); struct BTNode *pD = (struct BTNode *)malloc(sizeof(struct BTNode)); struct BTNode *pE = (struct BTNode *)malloc(sizeof(struct BTNode)); pA->data = ‘A‘; pA->data = ‘B‘; pA->data = ‘C‘; pA->data = ‘D‘; pA->data = ‘E‘; pA->pLchild = pB; pA->pRchild = pC; pB->pLchild = pB->pRchild = NULL; pC->pLchild = pD; pC->pRchild = NULL; pD->pLchild = NULL; pD->pRchild = pE; pE->pLchild = pE->pRchild = NULL; return pA; }