BiTree:
1 //链式结构二叉树 2 #include<iostream> 3 using namespace std; 4 #define MAXSIZE 100 5 typedef char ElemType; 6 7 typedef struct BitNode 8 { 9 ElemType data; 10 BitNode *lchild; 11 BitNode *rchild; 12 }*BiTree; 13 14 //构造空二叉树T 15 void InitBiTree(BiTree *T) 16 { 17 *T = NULL; 18 } 19 20 //销毁二叉树 21 void DestroyBiTree(BiTree *T) 22 { 23 if(*T) 24 { 25 if((*T)->lchild) 26 DestroyBiTree(&(*T)->lchild); 27 if((*T)->rchild) 28 DestroyBiTree(&(*T)->rchild); 29 delete(*T); 30 *T = NULL; 31 } 32 } 33 34 //生成二叉树 35 void CreateBiTree(BiTree *T) 36 { 37 ElemType ch; 38 if((ch=getchar())=='#') 39 *T = NULL; 40 else 41 { 42 *T = new BitNode; 43 (*T)->data = ch; 44 CreateBiTree(&(*T)->lchild); 45 CreateBiTree(&(*T)->rchild); 46 } 47 } 48 49 //判断是否为空 50 bool EmptyBiTree(BiTree T) 51 { 52 if(T) 53 { 54 cout<<"非空"<<endl; 55 return false; 56 } 57 else 58 { 59 cout<<"空"<<endl; 60 return true; 61 } 62 } 63 64 #define ClearBiTree DestroyBiTree 65 66 //求T深度 67 int DepthBiTree(BiTree *T) 68 { 69 int i; 70 int j; 71 if(!(*T)) 72 return 0; 73 if((*T)->lchild) 74 { 75 i = DepthBiTree(&(*T)->lchild); 76 //cout<<"L "<< i <<endl; 77 } 78 else 79 i = 0; 80 if((*T)->rchild) 81 { 82 j = DepthBiTree(&(*T)->rchild); 83 //cout<<"R "<< j <<endl; 84 } 85 else 86 j = 0; 87 return (i>j ? i+1 : j+1); 88 } 89 90 //返回二叉树的根 91 ElemType Root(BiTree T) 92 { 93 if(EmptyBiTree(T)) 94 return 0; 95 else 96 return (T)->data; 97 } 98 99 //返回p所指结点的值 100 ElemType Value(BiTree p) 101 { 102 return p->data; 103 } 104 105 //给p所指结点复制value 106 void Assign(BiTree p, ElemType value) 107 { 108 p->data = value; 109 } 110 111 //前序递归遍历T 112 void PreOrderTraverse(BiTree T) 113 { 114 if(T==NULL) 115 return; 116 cout<<T->data; 117 PreOrderTraverse(T->lchild); 118 PreOrderTraverse(T->rchild); 119 } 120 121 //中序递归遍历T 122 void InOrderTraverse(BiTree T) 123 { 124 if(T==NULL) 125 return; 126 PreOrderTraverse(T->lchild); 127 cout<<T->data; 128 PreOrderTraverse(T->rchild); 129 } 130 131 //后序递归遍历T 132 void PosOrderTraverse(BiTree T) 133 { 134 if(T==NULL) 135 return; 136 PreOrderTraverse(T->lchild); 137 PreOrderTraverse(T->rchild); 138 cout<<T->data; 139 } 140 141 int main() 142 { 143 BiTree T; 144 ElemType ch; 145 146 InitBiTree(&T); 147 CreateBiTree(&T); 148 EmptyBiTree(T); 149 int d = DepthBiTree(&T); 150 cout<<"二叉树深度:"<<d<<endl; 151 ch = Root(T); 152 cout<<"二叉树根:"<<ch<<endl; 153 154 cout<<"前序遍历:"; 155 PreOrderTraverse(T); 156 cout<<" 中序遍历:"; 157 InOrderTraverse(T); 158 cout<<" 后序遍历:"; 159 PosOrderTraverse(T); 160 161 ClearBiTree(&T); 162 cout<<" 二叉树为:"; 163 EmptyBiTree(T); 164 cout<<"二叉树深度:"<<DepthBiTree(&T)<<endl; 165 int i = Root(T); 166 if(!i) 167 cout<<"树空,无根。"<<endl; 168 169 return 0; 170 }