链式二叉树遍历具体程序
#include <stdio.h> struct BTNode { char data; struct BTNode * pLchild; //p是指针L是左,child是孩子 struct BTNode * pRchild; }; struct BTNode * CreateBTree(); void PreTraverseBTree(struct BTNode *); void PreTraverseBTree(struct BTNode *); void PostTraverseBTree(struct BTNode *); int main() { struct BTNode * pT = CreateBTree(); PreTraverseBTree(pT); InTraverseBTree(pT); PostTraverseBTree(pT); return 0; } void PreTraverseBTree(struct BTNode *pT) { if(pT!=NULL) //if必须要有,虽然pT存在,但当pT->pLchild 或 pT->pRchild为空时没有,空没有指向的data域 { printf("%c\n", pT->data); if(pT->pLchild!=NULL) PreTraverseBTree(pT->pLchild); if(pT->pRchild) PreTraverseBTree(pT->pRchild); } //pT->pLchild 可以代表整个左子树 /* 先访问根节点 再先序遍历左子树 再先序遍历右子树 */ } void InTraverseBTree(struct BTNode *pT) { if(pT!=NULL) //if必须要有,虽然pT存在,但当pT->pLchild 或 pT->pRchild为空时没有,空没有指向的data域 { if(pT->pLchild!=NULL) InTraverseBTree(pT->pLchild); printf("%c\n", pT->data); if(pT->pRchild) InTraverseBTree(pT->pRchild); } } void PostTraverseBTree(struct BTNode *pT) { if(pT!=NULL) //if必须要有,虽然pT存在,但当pT->pLchild 或 pT->pRchild为空时没有,空没有指向的data域 { if(pT->pLchild!=NULL) PostTraverseBTree(pT->pLchild); if(pT->pRchild) PostTraverseBTree(pT->pRchild); printf("%c\n", pT->data); } } struct BTNode * CreateBTree() { 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'; pB->data = 'B'; pC->data = 'C'; pD->data = 'D'; pE->data = 'E'; pA->pLchild = pB; pA->pRchild = pC; pB->pLchild = pB->pRchild =NULL; pC->pLchild = pD; pC->pRchild = NULL; pD->pRchild = pE; pD->pLchild = NULL; pE->pLchild = pE->pRchild = NULL; return pA; }