#include<iostream>
#include<stdlib.h>
using namespace std;
typedef char DataType;
typedef struct BitNode
{
DataType data;
struct BitNode *lchild,*rchild;
}*BitTree;
void BinTreeInit(BitTree &BT)// 初始化二叉树,即把树根指针置空
{
BT=(BitTree)malloc(sizeof(BitNode));
BT->data=NULL;
cout<<" 二叉树初始化成功 !"<<endl;
}
int BinTreeCreat(BitTree &BT)// 按先序次序建立一个二叉树
{
char ch;
cin>>ch;
if(ch=='#') BT=NULL;
else
{
if(!(BT=(BitTree)malloc(sizeof(BitNode))))
exit(0);
BT->data=ch;
BinTreeCreat(BT->lchild);
BinTreeCreat(BT->rchild);
}
//cout<<" 按先序序列建立一个二叉树已经完成 !"<<endl;
return 0;
//
}
void BinTreeEmpty(BitTree &BT)// 检查二叉树是否为空
{
if(BT->data==NULL)
cout<<" 是空二叉树 !"<<endl;
else
cout<<" 不是空二叉树 !"<<endl;
}
void BinTraverse(BitTree &BT)// 先序序列遍历二叉树
{
if(BT!=NULL)
{
cout<<BT->data;
BinTraverse(BT->lchild);
BinTraverse(BT->rchild);
}
}
void InOrderTraverse(BitTree &BT)//补充中序遍历二叉树
{
if(BT!=NULL)
{
InOrderTraverse(BT->lchild);
cout<<BT->data;
InOrderTraverse(BT->rchild);
}
}
void PostOrderTraverse(BitTree &BT)//补充后序遍历二叉树
{
if(BT!=NULL)
{
PostOrderTraverse(BT->lchild);
PostOrderTraverse(BT->rchild);
cout<<BT->data;
}
}
int BinTreeDepth(BitTree BT)// 求二叉树的深度
{
int depthval;
if(BT)
{
int depthLeft=BinTreeDepth(BT->lchild);
int depthRight=BinTreeDepth(BT->rchild);
depthval=1+(depthLeft>depthRight?depthLeft:depthRight);//左右子树深度大的+1
}
else depthval=0;//空树
return depthval;
}
int BinTreeCount(BitTree BT)// 求二叉树中所有结点数
{
int node;
if(BT)
{
int lchild=BinTreeCount(BT->lchild);
int rchild=BinTreeCount(BT->rchild);
node=lchild+rchild+1;
}
else
node=0;
return node;
}
void DestroyBinTree(BitTree &BT)//摧毁
{
if(BT!=NULL)
{
DestroyBinTree(BT->lchild);
DestroyBinTree(BT->rchild);
free (BT);
BT=NULL;
}
}
//
int main()
{
int i;
BitTree BT;
cout<<"1.初始化二叉树:"<<"\n2.按先序序列建立二叉树:"<<"\n3.判断二叉树是否为空:\n";
cout<<"4.先序序列遍历二叉树:"<<"\n5.中序遍历二叉树:"<<"\n6.后序遍历二叉树:\n";
cout<<"7.求二叉树的深度:\n8.求二叉树节点的个数:\n0.摧毁并退出"<<endl;
while(1)
{
cout<<" 输入你所需的操作 :";
cin>>i;
if(i==1)
BinTreeInit(BT);
else if(i==2)
{
cout<<" 输入你要建立的二叉树 :"<<endl;
BinTreeCreat(BT);
}
else if(i==3)
BinTreeEmpty(BT);
else if(i==4)
{
BinTraverse(BT);
cout<<"\n";
}
else if(i==5)
{
InOrderTraverse(BT);
cout<<"\n";
}
else if(i==6)
{
PostOrderTraverse(BT);
cout<<"\n";
}
else if(i==7)
cout<<" 二叉树的深度 :"<<BinTreeDepth(BT)<<endl;
else if(i==8)
cout<<" 二叉树的节点数 "<<BinTreeCount(BT)<<endl;
else
{
DestroyBinTree(BT);
cout<<"摧毁成功!\n";
return 0;
}
}
return 0;
}
数据结构-树的实现C++
最新推荐文章于 2024-06-14 14:44:45 发布