静态创建一个二叉树,分别采用前序遍历,中序遍历,后序遍历输出
1 /* 2 时间:2015年9月26日19:43:27 3 描述:静态创建二叉树,A做儿子为B,右儿子为C;B左右儿子为空;C左儿子为D,右儿子为空;D左儿子为空,右儿子为E;E左右儿子为空 4 功能:静态二叉树的创建,前序遍历,中序遍历,后序遍历 5 注意:malloc分配的内存没有释放! 6 */ 7 # include <stdio.h> 8 # include <malloc.h> 9 # include <stdlib.h> 10 11 struct BiTreeNode 12 { 13 char data;//数据域 14 struct BiTreeNode * pLchild;//指向左儿子 15 struct BiTreeNode * pRchild;//指向右儿子 16 }; 17 18 struct BiTreeNode * CreateBiTree(void); 19 void PreTraverse(struct BiTreeNode *);//前序遍历 20 void InTraverse(struct BiTreeNode *);//中序遍历 21 void PostTraverse(struct BiTreeNode *);//后序遍历 22 23 int main(void) 24 { 25 struct BiTreeNode * pT = CreateBiTree(); 26 printf("先序遍历: "); 27 PreTraverse(pT); 28 printf(" "); 29 30 printf("中序遍历: "); 31 InTraverse(pT); 32 printf(" "); 33 34 printf("后序遍历: "); 35 PostTraverse(pT); 36 printf(" "); 37 38 return 0; 39 } 40 41 //以下三种遍历方式,只需要调整 左 右 根 的顺序即可 42 void PostTraverse(struct BiTreeNode * pT)//左右根 43 { 44 if ( NULL != pT ) 45 { 46 if ( NULL != pT->pLchild ) 47 PostTraverse(pT->pLchild);//左 48 49 if ( NULL != pT->pRchild ) 50 PostTraverse(pT->pRchild);//右 51 52 printf("%c ", pT->data);//根 53 } 54 } 55 56 void InTraverse(struct BiTreeNode * pT)//左根右 57 { 58 if ( NULL != pT ) 59 { 60 if ( NULL != pT->pLchild ) 61 InTraverse(pT->pLchild); 62 63 printf("%c ", pT->data); 64 65 if ( NULL != pT->pRchild ) 66 InTraverse(pT->pRchild); 67 } 68 } 69 70 void PreTraverse(struct BiTreeNode * pT)//根左右 71 { 72 if ( NULL != pT ) 73 { 74 printf("%c ", pT->data); 75 76 if ( NULL != pT->pLchild ) 77 PreTraverse(pT->pLchild); 78 79 if ( NULL != pT->pRchild ) 80 PreTraverse(pT->pRchild); 81 } 82 } 83 84 struct BiTreeNode * CreateBiTree(void)//静态创建树,并返回根节点 85 { 86 struct BiTreeNode * pA = (struct BiTreeNode * )malloc(sizeof(struct BiTreeNode));//创建5个节点 87 struct BiTreeNode * pB = (struct BiTreeNode * )malloc(sizeof(struct BiTreeNode)); 88 struct BiTreeNode * pC = (struct BiTreeNode * )malloc(sizeof(struct BiTreeNode)); 89 struct BiTreeNode * pD = (struct BiTreeNode * )malloc(sizeof(struct BiTreeNode)); 90 struct BiTreeNode * pE = (struct BiTreeNode * )malloc(sizeof(struct BiTreeNode)); 91 if ( NULL == pA || NULL == pB || NULL == pC || NULL == pD || NULL == pE ) 92 { 93 printf("内存分配失败! "); 94 exit(-1); 95 } 96 pA->data = 'A';//给5个节点赋值 97 pB->data = 'B'; 98 pC->data = 'C'; 99 pD->data = 'D'; 100 pE->data = 'E'; 101 102 pA->pLchild = pB;//建立节点之间的关系 103 pA->pRchild = pC; 104 pB->pLchild = pB->pRchild = NULL; 105 pC->pLchild = pD; 106 pC->pRchild = NULL; 107 pD->pLchild = NULL; 108 pD->pRchild = pE; 109 pE->pLchild = pE->pRchild = NULL; 110 111 return pA;//返回根节点 112 } 113 114 /* 115 在VC++6.0输出结果是: 116 ---------------------------- 117 先序遍历: 118 A B C D E 119 中序遍历: 120 B A D E C 121 后序遍历: 122 B E D C A 123 Press any key to continue 124 ---------------------------- 125 */