本篇文章记录上周数据结构的实验课内容。
1.如何建树。
2.二叉树的先中后序以及层次遍历的实现。
3.计算二叉树深度。
4.计算二叉树的总结点数,以及分别计算度为0,1,2的结点数。
代码如下:
#include<bits/stdc++.h>
using namespace std;
int sumcount0=0;
int sumcount1=0;
int sumcount2=0;
char ch;
int m=0,n=0;
typedef int status;
typedef char TEleType;
typedef struct BiTNode{
TEleType data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
void CreatBiTree(BiTree &T)
{
cin>>ch;
if(ch=='#') T=NULL;
else
{
T=new BiTNode;
T->data=ch;
CreatBiTree(T->lchild);
CreatBiTree(T->rchild);
}
}//读入数据,创建二叉链表
void DLR(BiTree T)
{
if(T)
{
cout<<T->data;
DLR(T->lchild);
DLR(T->rchild);
}
} //先序遍历
void LDR(BiTree T)
{
if(T)
{
LDR(T->lchild);
cout<<T->data;
LDR(T->rchild);
}
} //中序遍历
void LRD(BiTree T)
{
if(T)
{
LRD(T->lchild);
LRD(T->rchild);
cout<<T->data;
}
} //后序遍历
void level(BiTree T)
{
if(T==NULL) return ;
queue<BiTree> q;
q.push(T);
while(!q.empty())
{
BiTree s=q.front();
q.pop();
cout<<s->data;
if(s->lchild!=NULL) q.push(s->lchild);
if(s->rchild!=NULL) q.push(s->rchild);
}
} //层次遍历
int depth(BiTree T)
{
if(T==NULL) return 0;
else{
m=depth(T->lchild);
n=depth(T->rchild);
if(m>n) return(m+1);
else return(n+1);
}
} //计算树的深度
int nodeCount(BiTree T)
{
if(T==NULL) return 0;
else{
return nodeCount(T->lchild)+nodeCount(T->rchild)+1;
}
}//计算总的结点数
int nodeCount0(BiTree T)
{
if(T)
{
if(T->lchild==NULL&&T->rchild==NULL)
{
sumcount0++;
}
nodeCount0(T->lchild);
nodeCount0(T->rchild);
}
return sumcount0;
}//统计度为0的结点数
int nodeCount1(BiTree T)
{
if(T)
{
if((T->lchild==NULL&&T->rchild!=NULL)||(T->lchild!=NULL&&T->rchild==NULL))
sumcount1++;
nodeCount1(T->lchild);
nodeCount1(T->rchild);
}
return sumcount1;
}//统计度为1的结点数
int nodeCount2(BiTree T)
{
if(T)
{
if(T->lchild!=NULL&&T->rchild!=NULL)
sumcount2++;
nodeCount2(T->lchild);
nodeCount2(T->rchild);
}
return sumcount2;
}//统计度为2的结点数
int main()
{
cout<<"请选择你要进行的操作:"<<endl;
cout<<endl;
cout<<"1:建立二叉树"<<endl;
cout<<"2:二叉树的先序遍历,中序遍历,后序遍历,层次遍历结果"<<endl;
cout<<"3:二叉树的深度"<<endl;
cout<<"4:二叉树的总结点数,度为0的结点数,度为1的结点数,度为2的结点数:"<<endl;
cout<<endl;
int ch;
cin>>ch;
BiTree T=NULL;
while(ch!=5)
{
switch(ch)
{//AB#CD##E##F#GH###
case 1:cout<<"请输入二叉树的数据:"<<endl;
CreatBiTree(T);
cout<<"二叉树建立成功"<<endl;
break;
case 2:cout<<"先序遍历结果为:";
DLR(T);
cout<<endl;
cout<<"中序遍历结果为:";
LDR(T);
cout<<endl;
cout<<"后序遍历结果为:";
LRD(T);
cout<<endl;
cout<<"层次遍历结果为:";
level(T);
cout<<endl;
break;
case 3:cout<<"二叉树的深度为:";
cout<<depth(T);
cout<<endl;
break;
case 4:cout<<"二叉树中所有结点数之和为:";
cout<<nodeCount(T);
cout<<endl;
cout<<"二叉树中度为0的结点数为:";
cout<<nodeCount0(T);
cout<<endl;
cout<<"二叉树中度为1的结点数为:";
cout<<nodeCount1(T);
cout<<endl;
cout<<"二叉树中度为2的结点数为:";
cout<<nodeCount2(T);
cout<<endl;
break;
}
cin>>ch;
}
return 0;
}