#include<iostream>
using namespace std;
typedef struct BITNode{
char data;
struct BITNode *lchild,*rchild;
}BITNode,*BITree;
void Creat(BITNode* &T){ ///以先序遍历的顺序建立二叉树
char ch;cin>>ch;
if(ch=='#')T=NULL;
else{
T=new BITNode;
T->data=ch;
Creat(T->lchild);
Creat(T->rchild);
}
}
void PreOrder(BITNode* T){ ///先序遍历输出
if(T){
cout<<T->data;
PreOrder(T->lchild);
PreOrder(T->rchild);
}
}
void InOrder(BITNode* T){ ///中序遍历输出
if(T){
InOrder(T->lchild);
cout<<T->data;
InOrder(T->rchild);
}
}
void PostOrder(BITNode* T){ ///后序遍历输出
if(T){
PostOrder(T->lchild);
PostOrder(T->rchild);
cout<<T->data;
}
}
int NodeCount(BITNode* T){ ///计算结点个数
if(T==NULL)return 0;
else return NodeCount(T->lchild)+NodeCount(T->rchild)+1;
}
void LeafCount(BITNode* T,int &num){ ///计算叶子个数
if(T==NULL){
return;
}
if(T->lchild==NULL&&T->rchild==NULL){
num+=1;
return;
}
LeafCount(T->lchild,num);
LeafCount(T->rchild,num);
}
void DeleteTree(BITNode* &T) ///销毁树
{
if(T==NULL)
return;
DeleteTree(T->lchild);
DeleteTree(T->rchild);
delete T;
}
void menu(){
cout<<"菜单:\n";
cout<<"1.建立二叉树\t\t";cout<<"2.先序遍历输出\n";
cout<<"3.中序遍历输出\t\t";cout<<"4.后序遍历输出\n";
cout<<"5.二叉树结点个数\t";cout<<"6.二叉树叶子个数\n";
cout<<"0.退出\n";
}
int main()
{
BITree Tree;
menu();
int choose=-1;
while(choose){
cout<<"\n请输入命令:";
cin>>choose;
switch(choose){
case 1:
cout<<"请输入建立二叉链表的序列:\n";
Creat(Tree);
break;
case 2:
PreOrder(Tree);
cout<<endl;
break;
case 3:
InOrder(Tree);
cout<<endl;
break;
case 4:
PostOrder(Tree);
cout<<endl;
break;
case 5:
cout<<"二叉树结点个数为:"<<NodeCount(Tree)<<endl;
break;
case 6:
int num=0;
LeafCount(Tree,num);
cout<<"二叉树叶子个数为:"<<num<<endl;
break;
}
}
DeleteTree(Tree);
cout<<"退出成功\n";
return 0;
}
/*
A
B
C
#
#
D
E
#
G
#
#
F
#
#
#
*/
实验三:二叉树基本操作的实现
最新推荐文章于 2023-06-04 15:00:00 发布