1. 程式人生 > 其它 >二叉樹的建立,遍歷(一)

二叉樹的建立,遍歷(一)

在進行建立或遍歷時一定得知道遞迴正真原理,能在腦子中構思出來,這樣也能更簡單得轉化成非遞迴的形式;接下來的文章我會不斷講解;

 1 #include<cstdio>
 2 #include <iostream>
 3 #include<cstring>
 4 #define size 50
 5 using namespace std;
 6 typedef struct BitNode1 {
 7     char Data;
 8     struct BitNode1* lchild, * rchild;
 9 }BitNode1,*BitNode;
10 /****************內容,先序遍歷、中序遍歷、後序遍歷,以及以上遍歷的非遞迴形式程式碼,層次遍歷,還有線索二叉樹會單獨拉出一個專案編寫******************/ 11 //遞迴先序建立二叉樹; 12 void CreatorderTree(BitNode& T) 13 { 14 char ch[size]; 15 int i = 0; 16 cin >> ch; 17 for(int i=0;i<strlen(ch);i++) 18 { 19 if (ch[i]=='*') 20 T = NULL;
21 else 22 { 23 T = new BitNode1; 24 T->Data = ch[i++]; 25 CreatorderTree(T->lchild); 26 CreatorderTree(T->rchild); 27 } 28 } 29 } 30 void Visit(BitNode& T) 31 { 32 cout << T->Data << ' '; 33 }
34 void PreOreder(BitNode& T)//先序遞迴 35 { 36 if (T) { 37 Visit(T); 38 PreOreder(T->lchild); 39 PreOreder(T->rchild); 40 } 41 } 42 void InOrder(BitNode& T)//中序遞迴 43 { 44 if (T) { 45 InOrder(T->lchild); 46 Visit(T); 47 InOrder(T->rchild); 48 } 49 } 50 void PostOrder(BitNode& T)//後序遞迴 51 { 52 if (T) { 53 PostOrder(T->lchild); 54 PostOrder(T->rchild); 55 Visit(T); 56 } 57 } 58 void LevelOrder(BitNode& T)//層次佇列 59 { 60 61 } 62 int main() 63 { 64 BitNode1 *T; 65 CreatorderTree(T); 66 PreOreder(T); 67 cout << endl; 68 InOrder(T); 69 cout << endl; 70 PostOrder(T); 71 cout << endl; 72 return 0; 73 }