1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<malloc.h> 4 5 typedef struct Node//結構體 6 { 7 char data; 8 struct Node *LChild; 9 struct Node *RChild; 10 } BinNode,*BinTree; 11 12 BinTree CreateTree(BinTree T) 13 { 14 char ch; 15 scanf("%c",&ch); 16 if(ch=='#') 17 return NULL; 18 else 19 { 20 T=(BinTree)malloc(sizeof(BinNode)); 21 T->data=ch; 22 T->LChild=CreateTree(T->LChild);/*創建左子樹*/ 23 T->RChild=CreateTree(T->RChild);/*創建右子樹*/ 24 return T; 25 } 26 } 27 28 void PreOrder(BinTree root)//先序遍歷 29 { 30 if (root != NULL) 31 { 32 printf("%c", root->data); 33 PreOrder(root->LChild); 34 PreOrder(root->RChild); 35 } 36 } 37 38 void InOrder(BinTree root)//中序遍歷 39 { 40 if (root != NULL) 41 { 42 InOrder(root->LChild); 43 printf("%c", root->data); 44 InOrder(root->RChild); 45 } 46 } 47 48 void PostOrder(BinTree root)//后序遍歷 49 { 50 if (root != NULL) 51 { 52 PostOrder(root->LChild); 53 PostOrder(root->RChild); 54 printf("%c", root->data); 55 } 56 } 57 /*求二叉樹結點總數*/ 58 int Count(BinTree T) 59 { 60 if(T==NULL) 61 return 0; /*空二叉樹結點數為0*/ 62 else /*左右子樹結點總數加1*/ 63 return Count(T->LChild)+Count(T->RChild)+1; 64 } 65 //葉子數 66 int LeafCount(BinTree T){ 67 if(T == NULL){ 68 return 0; 69 } 70 else if ((T->LChild==NULL) && (T->RChild==NULL)){ 71 return 1; 72 } 73 else{ 74 return LeafCount(T->LChild)+LeafCount(T->RChild); 75 } 76 } 77 int main() 78 { 79 80 BinTree bt; 81 printf("一、請按先序的方式輸入二叉樹的結點元素(注:輸入#表示節點為空)如:ABC##DE#G##F###\n"); 82 bt=CreateTree(bt); 83 printf("二、前序遍歷二叉樹:\n"); 84 PreOrder(bt); 85 printf("\n"); 86 printf("三、中序遍歷二叉樹:\n"); 87 InOrder(bt); 88 printf("\n"); 89 printf("四、后序遍歷二叉樹:\n"); 90 PostOrder(bt); 91 printf("\n"); 92 printf("五、二叉樹結點數: %d\n",Count(bt)); 93 printf("六、葉子節點的個數:%d \n",LeafCount(bt)); 94 system("pause"); 95 }
