數據結構課程實驗作業
代碼:
1 #include <iostream> 2 #include <malloc.h> 3 #include <queue> 4 using namespace std; 5 6 typedef char TElemtype; 7 typedef struct BiTnode{ 8 TElemtype data; 9 struct BiTnode *lchild, *rchild; 10 }*Tree, Btree; 11 12 void create(Tree &tree){//創建二叉樹 13 tree=(Btree *)malloc(sizeof(Btree)); 14 cin >> tree->data; 15 if(tree->data=='#'){ 16 tree=NULL; 17 return; 18 } 19 create(tree->lchild); 20 create(tree->rchild); 21 } 22 23 void preorder_traversal(Tree tree){//先序遍歷 24 if(!tree) return; 25 cout << tree->data << " "; 26 preorder_traversal(tree->lchild); 27 preorder_traversal(tree->rchild); 28 } 29 30 void inorder_traversal(Tree tree){ 31 if(!tree) return; 32 inorder_traversal(tree->lchild); 33 cout << tree->data << " "; 34 inorder_traversal(tree->rchild); 35 } 36 37 void postorder_traversal(Tree tree){//後序遍歷 38 if(!tree) return; 39 postorder_traversal(tree->lchild); 40 postorder_traversal(tree->rchild); 41 cout << tree->data << " "; 42 } 43 44 void hierarchical_traversal(Tree tree){//***層次遍歷 45 queue<Tree> q; 46 q.push(tree); 47 while(!q.empty()){ 48 Tree cnt=q.front(); 49 q.pop(); 50 cout << cnt->data << " "; 51 if(cnt->lchild) q.push(cnt->lchild); 52 if(cnt->rchild) q.push(cnt->rchild); 53 } 54 } 55 56 int main(void){ 57 Tree tree; 58 cout << "以先序順序輸入初始字符串,#表示當前位置爲空: " << endl; 59 create(tree);//創建二叉樹 60 cout << "先序遍歷: " << endl; 61 preorder_traversal(tree);//先序遍歷 62 cout << endl; 63 cout << "中序遍歷: " << endl; 64 inorder_traversal(tree);//中序遍歷 65 cout << endl; 66 cout << "後序遍歷:" << endl; 67 postorder_traversal(tree);//後序遍歷 68 cout << endl; 69 cout << "層次遍歷:" << endl; 70 hierarchical_traversal(tree);//層次遍歷 71 cout << endl; 72 return 0; 73 }