1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
|
#include <stdio.h> #include <stdlib.h>
typedef struct BTNode{ char data; struct BTNode * pLeft; struct BTNode * pRight; }BTNode;
struct BTNode * createBTree(void); void PreTraverseBTree(struct BTNode * pT); void InTraverseBTree(struct BTNode * pT); void PostTraverseBTree(struct BTNode * pT);
int main(){ struct BTNode * pT = createBTree(); printf("该二叉树的前序遍历为:\n"); PreTraverseBTree(pT); printf("\n该二叉树的中序遍历为:\n");
printf("\n该二叉树的后序遍历为:\n"); PostTraverseBTree(pT); printf("\n"); return 0; }
struct BTNode * createBTree(){ BTNode * pA = (struct BTNode*)malloc(sizeof(BTNode)); BTNode * pB = (struct BTNode*)malloc(sizeof(BTNode)); BTNode * pC = (struct BTNode*)malloc(sizeof(BTNode)); BTNode * pD = (struct BTNode*)malloc(sizeof(BTNode)); BTNode * pE = (struct BTNode*)malloc(sizeof(BTNode)); pA->data = 'A'; pB->data = 'B'; pC->data = 'C'; pD->data = 'D'; pE->data = 'E'; pA->pLeft = pB; pA->pRight = pC; pB->pLeft = pB->pRight = NULL; pC->pLeft = pD; pC->pRight = NULL; pD->pLeft = NULL; pD->pRight = pE; pE->pLeft = pE->pRight = NULL; return pA; }
void PreTraverseBTree(struct BTNode * pT){ if(pT != NULL){ printf("%c ",pT->data); if(pT->pLeft != NULL){ PreTraverseBTree(pT->pLeft); } if(pT->pRight != NULL){ PreTraverseBTree(pT->pRight); } } }
void InTraverseBTree(struct BTNode * pT){ if(pT != NULL){ if(pT->pLeft != NULL){ InTraverseBTree(pT->pLeft); } printf("%c ",pT->data); if(pT->pRight != NULL){ InTraverseBTree(pT->pRight); } } }
void PostTraverseBTree(struct BTNode * pT){ if(pT != NULL){ if(pT->pLeft != NULL){ PostTraverseBTree(pT->pLeft); } if(pT->pRight != NULL){ PostTraverseBTree(pT->pRight); } printf("%c ",pT->data); } }
|