遞迴先序、非遞迴層次建立二叉樹並用三序遍歷之(C語言)
阿新 • • 發佈:2018-12-26
先序就是直接用遞迴的方法建立,層次使用了輔助陣列,後一種方法我覺得友好多了。
#include "stdio.h" #define MAXSIZE 50 #define TRUE 1 #define FALSE 0 typedef int bool; //Cpp中這一行要取消掉,他內建bool型 typedef int Status; //函式型別,其值是函式結果狀態碼 typedef char ElemType; //資料型別 typedef struct BinTree //定義二叉樹結構 { ElemType Data; struct BinTree *LChild,*RChild; }BTNode; void vist( ElemType Temp) { printf("%c ",Temp); } void Pre(BTNode *BT)//先序遍歷 { if(BT) { vist(BT->Data); Pre(BT->LChild); Pre(BT->RChild); } } void In(BTNode *BT)//中序遍歷 { if(BT) { In(BT->LChild); vist(BT->Data); In(BT->RChild); } } void Post(BTNode *BT)//後序遍歷 { if(BT) { Post(BT->LChild); Post(BT->RChild); vist(BT->Data); } } BTNode * LevelCreate()//按層次遍歷建樹 { printf("*******層 次 遍 歷 建 樹*******\n"); printf("*編號數字,結點值字母,0結束。*\n\n\n"); BTNode *T,*p,*s[MAXSIZE]; char ch; int i,j,cnt=0; while (1) { if(cnt%2==0) { printf("請輸入編號:"); cnt++; } else{ printf("請輸入結點值:"); cnt++; } scanf("%d",&i); if(i==0) break; else { ch=getchar(); p=(BTNode*)malloc(sizeof(BTNode)); p->Data=ch; p->LChild=p->RChild=NULL; s[i]=p; if (i==1) T=p; else { j=i/2; if(i%2==0) s[j]->LChild=p; else s[j]->RChild=p; } } } return (T); } BTNode *PreCreate() //先序建樹,輸入*代表那個結點不存豐。 { char ch; BTNode *T; scanf("%c",&ch); if(ch!='*') { T=(BTNode*)malloc(sizeof(BTNode)); T->Data=ch; T->LChild=PreCreate(); T->RChild=PreCreate(); } else { T=NULL; //為零則不存在 } return T; } int main() { BTNode *TRoot,*PRoot; printf("#########先序遍歷建樹#########\n"); printf("請一次輸入全部結點值,空結點為*.\n"); printf("如樹序列123,則輸入123****\n"); printf("\n\請輸入:"); TRoot=PreCreate(); printf("先序遍歷:"); Pre(TRoot); printf("\n中序遍歷:"); In(TRoot); printf("\n後序遍歷:"); Post(TRoot); printf("\n"); PRoot=LevelCreate(); printf("先序遍歷:"); Pre(PRoot); printf("\n中序遍歷:"); In(PRoot); printf("\n後序遍歷:"); Post(PRoot); printf("\n\n\n"); getchar(); return 0; }
執行效果如下圖: