1 #include<iostream> 2 using namespace std; 3 struct BiNode //定义结点 4 { 5 char data; //数据类型 6 BiNode *lchild, *rchild; //左子结点和右子结点 7 }; 8 class BiTree 9 { 10 public: 11 BiTree(){ root = Creat(root); } //构造函数,创建二叉树 12 ~BiTree(){ Release(root); } //析构函数,释放存储空间 13 void PreOrder(){ PreOrder(root); } //前序遍历 14 void InOrder(){ InOrder(root); } //中序遍历 15 void PostOrder(){ PostOrder(root); } //后序遍历 16 void LeverOrder(); //层序遍历 17 int CountLeaf(){ return CountLeaf(root); } //返回叶子结点数 18 19 private: 20 BiNode *root; //设置头结点 21 BiNode *Creat(BiNode *bt); //构造函数调用 22 void Release(BiNode *bt); //析构函数调用 23 void PreOrder(BiNode *bt); //前序遍历函数调用 24 void InOrder(BiNode *bt); //中序遍历函数调用 25 void PostOrder(BiNode *bt); //后序遍历函数调用 26 int CountLeaf(BiNode *bt); // 返回叶子结点函数调用 27 }; 28 29 //创建二叉树 30 BiNode *BiTree::Creat(BiNode *bt) 31 { 32 char ch; 33 cin >> ch; 34 if (ch == '#')bt = NULL; 35 else{ 36 bt = new BiNode; bt->data = ch; //生成新结点,数据域为ch 37 bt->lchild = Creat(bt->lchild); //递归建立左子树 38 bt->rchild = Creat(bt->rchild); //递归建立右子树 39 } 40 return bt; 41 } 42 43 //析构函数释放结点 44 void BiTree::Release(BiNode *bt) 45 { 46 if (bt != NULL){ 47 Release(bt->lchild); 48 Release(bt->rchild); 49 delete bt; 50 } 51 } 52 void BiTree::PreOrder(BiNode *bt) 53 { 54 if (bt == NULL)return; 55 else{ 56 cout << bt->data; 57 PreOrder(bt->lchild); 58 PreOrder(bt->rchild); 59 } 60 } 61 void BiTree::InOrder(BiNode *bt) 62 { 63 if (bt == NULL)return; 64 else{ 65 InOrder(bt->lchild); 66 cout << bt->data; 67 InOrder(bt->rchild); 68 } 69 } 70 void BiTree::PostOrder(BiNode *bt) 71 { 72 if (bt == NULL)return; 73 else{ 74 PostOrder(bt->lchild); 75 PostOrder(bt->rchild); 76 cout << bt->data; 77 } 78 } 79 void BiTree::LeverOrder() 80 { 81 const int MaxSize = 100; 82 BiNode *Q[MaxSize], *q; 83 int front, rear; 84 front = rear = -1; 85 if (root == NULL)return; 86 Q[++rear] = root; 87 while (front != rear) 88 { 89 q = Q[++front]; 90 cout << q->data; 91 if (q->lchild != NULL) Q[++rear] = q->lchild; 92 if (q->rchild != NULL) Q[++rear] = q->rchild; 93 } 94 } 95 int BiTree::CountLeaf(BiNode *bt) 96 { 97 static int count = 0; 98 if (bt != NULL) 99 { 100 if (bt->lchild == NULL&&bt->rchild == NULL) 101 { 102 count++; 103 } 104 CountLeaf(bt->lchild); 105 CountLeaf(bt->rchild); 106 return count; 107 } 108 } 109 void main() 110 { 111 BiTree T; 112 cout << "-----前序遍历----" << endl; 113 T.PreOrder(); 114 cout << endl; 115 116 cout << "-----中序遍历----" << endl; 117 T.InOrder(); 118 cout << endl; 119 120 cout << "-----后序遍历----" << endl; 121 T.PostOrder(); 122 cout << endl; 123 124 cout << "-----层序遍历----" << endl; 125 T.LeverOrder(); 126 cout << endl; 127 128 cout << "叶子结点的个数为:" << T.CountLeaf() << endl; 129 }