二叉树的创建,遍历(一)
在进行创建或遍历时一定得知道递归正真原理,能在脑子中构思出来,这样也能更简单得转化成非递归的形式;接下来的文章我会不断讲解;
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 typedef struct Queue { 13 BitNode Data[size]; 14 int top; 15 int bottom; 16 }Queue; 17 void InitQueue(Queue& L) 18 { 19 L.bottom = L.top = 0; 20 } 21 void EnQueue(Queue& L,BitNode T) 22 { 23 L.Data[L.top++] = T; 24 } 25 void DeQueue(Queue& L,BitNode &T) 26 { 27 T = L.Data[L.bottom++]; 28 } 29 bool EmptyQueue(Queue& L) 30 { 31 if (L.bottom == L.top) return true; 32 return false; 33 } 34 void CreatorderTree(BitNode& T) 35 { 36 char ch[size]; 37 int i = 0; 38 cin >> ch; 39 if (ch[i]=='*') 40 T = NULL; 41 else 42 { 43 T = new BitNode1; 44 T->Data = ch[i++]; 45 CreatorderTree(T->lchild); 46 CreatorderTree(T->rchild); 47 } 48 } 49 void Visit(BitNode& T) 50 { 51 cout << T->Data << ' '; 52 } 53 void PreOreder(BitNode& T)//先序递归 54 { 55 if (T) { 56 Visit(T); 57 PreOreder(T->lchild); 58 PreOreder(T->rchild); 59 } 60 } 61 void InOrder(BitNode& T)//中序递归 62 { 63 if (T) { 64 InOrder(T->lchild); 65 Visit(T); 66 InOrder(T->rchild); 67 } 68 } 69 void PostOrder(BitNode& T)//后序递归 70 { 71 if (T) { 72 PostOrder(T->lchild); 73 PostOrder(T->rchild); 74 Visit(T); 75 } 76 } 77 void LevelOrder(BitNode& T)//层次队列 78 { 79 Queue Q; 80 InitQueue(Q); 81 BitNode P=NULL; 82 EnQueue(Q, T); 83 while (!EmptyQueue(Q)) 84 { 85 DeQueue(Q, P); 86 Visit(P); 87 if (P->lchild) EnQueue(Q, P->lchild); 88 if (P->rchild) EnQueue(Q, P->rchild); 89 } 90 } 91 int main() 92 { 93 BitNode1 *T; 94 CreatorderTree(T); 95 PreOreder(T); 96 cout << endl; 97 InOrder(T); 98 cout << endl; 99 PostOrder(T); 100 cout << endl; 101 LevelOrder(T); 102 return 0; 103 }

浙公网安备 33010602011771号