一、实验目的
掌握二叉树的遍历算法,熟练使用遍历算法进行问题的求解。
二、实验内容
对于给定的字符串“ABF#C#G##DE##H###”,用递归的方法实现以下算法:
(1)以二叉链表表示二叉树,建立一棵二叉树;
(2)输出二叉树的中序遍历结果;
(3)输出结点“C”的左右孩子的值;
(4)计算二叉树的深度;
(5)统计二叉树的叶子结点个数;
(6)统计二叉树的度为1的结点个数;
头文件与以二叉链表建立二叉树:
#include<iostream>
using namespace std;
typedef struct bitnode{
char date;
struct bitnode *lchild,*rchild;
}bitnode,*bitree;
菜单子函数,用于交互:
void menu(){
cout<<"1.输出二叉树的中序遍历结果!"<<endl;
cout<<"2.输出结点“C”的左右孩子的值!"<<endl;
cout<<"3.计算二叉树的深度!"<<endl;
cout<<"4.统计二叉树的叶子结点个数!"<<endl;
cout<<"5.统计二叉树的度为1的结点个数!"<<endl;
cout<<"0.退出!"<<endl;
}
以先序遍历的方式建立二叉树:
void creatbitree(bitree &t){//先序遍历的顺序创建二叉树
char ch;
cin>>ch;
if(ch=='#') t=NULL;
else{
t=new bitnode;
t->date=ch;
creatbitree(t->lchild);
creatbitree(t->rchild);
}
}
以中序遍历输出二叉树:
void inordertraverse(bitree t){//以中序遍历输出二叉树
if(t){
ABF#C#G##DE##H###
inordertraverse(t->lchild);
cout<<t->date;
inordertraverse(t->rchild);
}
else cout<<"#";
}
输出结点C的左右孩子(C在主函数中以char的类型传入):
void lrchild(bitree t,char c){//输出结点C的左右孩子
if(t){
if(t->date==c){
if(t->lchild) cout<<"结点处的左孩子为"<<t->lchild->date<<endl;
else cout<<c<<"结点处的左孩子为空"<<endl;
if(t->rchild) cout<<"结点处的右孩子为"<<t->rchild->date<<endl;
else cout<<c<<"结点处的右孩子为空"<<endl;
}
else{
lrchild(t->lchild,c);
lrchild(t->rchild,c);
}
}
}
计算二叉树的深度:
int depth(bitree t){
int m,n;
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 leaf(bitree t){
if(t){
if(!(leaf(t->lchild)||leaf(t->rchild))) return 1;
else return(leaf(t->lchild)+leaf(t->rchild));
}
else return 0;
}
统计二叉树中度为1的结点个数:
int lnode1(bitree t){
if(t){
if((!(t->lchild)&&(t->rchild))||((t->lchild)&&!(t->rchild)))
return 1+lnode1(t->lchild)+lnode1(t->rchild);
else return lnode1(t->lchild)+lnode1(t->rchild);
}
else return 0;
}
主函数:
int main()
{
bitree t;
int choose;
char c;
cout<<"以先序遍历的顺序创建二叉树!"<<endl<<"请输入一序列字符串!"<<endl;
creatbitree(t);
menu();
cout<<"请选择您所需要的操作:";
cin>>choose;
while(choose){
switch(choose){
case 1:
inordertraverse(t);
cout<<endl;
break;
case 2:
cout<<"请输入查询结点的值"<<endl;
cin>>c;
lrchild(t,c);
break;
case 3:
cout<<"该二叉树的深度为:"<<depth(t)<<endl;
break;
case 4:
cout<<"该二叉树的叶子结点个数为:"<<leaf(t)<<endl;
break;
case 5:
cout<<"该二叉树度为1的结点个数为:"<<lnode1(t)<<endl;
break;
default :
cout<<"选择操作错误!"<<endl;
break;
}
cout<<"请选择您所需要的操作:";
cin>>choose;
}
cout<<"感谢您的使用!"<<endl;
}
实验结果:
注意:二叉树的所有操作都是在递归的基础上实现的,因此需要注意函数实现的顺序!