数据结构躬行记5_数据结构_二叉树及其基本操作(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 }

 

posted @ 2020-09-16 22:39  17_Xtreme  阅读(165)  评论(0编辑  收藏  举报