1. 程式人生 > 實用技巧 >資料結構_二叉樹及其基本操作(c++)

資料結構_二叉樹及其基本操作(c++)

二叉樹

概念

二叉樹(Binary tree)是樹形結構的一個重要型別。許多實際問題抽象出來的資料結構往往是二叉樹形式,即使是一般的樹也能簡單地轉換為二叉樹,而且二叉樹的儲存結構及其演算法都較為簡單,因此二叉樹顯得特別重要。二叉樹特點是每個結點最多隻能有兩棵子樹,且有左右之分。

要點

二叉樹的建立和遍歷包含了一種很重要的思想那就是遞迴,遍歷包含:先序遍歷,中序遍歷,後續遍歷,遞迴建立的時候也必須先指定一種建立順序。

程式碼實現

  1 #include<iostream>
  2 using namespace std;
  3 typedef string eletype;
  4
typedef struct BiNode 5 { 6 eletype data; 7 struct BiNode *lchild,*rchild; 8 }BiNode,*BiTree; 9 10 void creatBiTree(BiTree &t) 11 { 12 string m; 13 cin>>m; 14 if(m =="#" ) 15 t =NULL; 16 else{ 17 t = new BiNode; 18 t->data = m;
19 creatBiTree(t->lchild); 20 creatBiTree(t->rchild); 21 } 22 23 } 24 25 void showBitree_zx(BiTree t) 26 { 27 if(t==NULL){ 28 29 }else{ 30 showBitree_zx(t->lchild); 31 cout<<t->data<<" "; 32 showBitree_zx(t->rchild); 33
} 34 } 35 36 void showBitree_xx(BiTree t) 37 { 38 if(t==NULL){ 39 40 }else{ 41 cout<<t->data<<" "; 42 showBitree_xx(t->lchild); 43 showBitree_xx(t->rchild); 44 } 45 } 46 47 void showBitree_hx(BiTree t) 48 { 49 if(t==NULL){ 50 51 }else{ 52 showBitree_hx(t->lchild); 53 showBitree_hx(t->rchild); 54 cout<<t->data<<" "; 55 } 56 } 57 58 int Depth(BiTree t) 59 { 60 int m,n; 61 if(t == NULL){ 62 return 0; 63 }else{ 64 m =Depth(t->lchild); 65 n=Depth(t->rchild); 66 if(m>n) 67 { 68 return m+1; 69 } 70 else{ 71 return n+1; 72 } 73 } 74 } 75 76 int NodeCount(BiTree t) 77 { 78 if(t ==NULL){ 79 return 0; 80 } 81 else{ 82 return NodeCount(t->lchild)+NodeCount(t->rchild)+1; 83 } 84 } 85 86 int main() 87 { 88 BiTree t = new BiNode; 89 cout<<"請按照先序的順序輸入節點資料(#代表為空):"<<endl; 90 creatBiTree(t); 91 92 cout<<"中序遍歷:"; 93 showBitree_zx(t); 94 cout<<endl; 95 96 cout<<"先序遍歷:"; 97 showBitree_xx(t); 98 cout<<endl; 99 100 cout<<"後序遍歷:"; 101 showBitree_hx(t); 102 cout<<endl; 103 104 cout<<"此二叉樹的深度是:"<<Depth(t); 105 cout<<endl; 106 107 cout<<"此二叉樹的結點個數是:"<<NodeCount(t); 108 cout<<endl; 109 110 return 0; 111 }