#include <iostream>
using namespace std;
struct binode
{
char data;
binode*lchild,*rchild;
};
class bitree
{
public:
bitree(){root=creat(root);}
~bitree(){release(root);}
void preorder(){preorder(root);}
void inorder(){inorder(root);}
void postorder(){postorder(root);}
int num(){num(root);}
int depth(){depth(root);}
int yznum(){yznum(root);}
void ex(){ex(root);}
private:
binode*creat(binode *bt);
void release(binode *bt);
void preorder(binode *bt);
void inorder(binode *bt);
void postorder(binode *bt);
int num(binode *bt);
int depth(binode *bt);
int yznum(binode *bt);
void ex(binode*bt);
binode *root;
};
void bitree::ex(binode *bt)
{
if(bt==NULL)
{
return ;
}
else
{
binode *temp=bt->lchild;
bt->lchild=bt->rchild;
bt->rchild=temp;
ex(bt->lchild);
ex(bt->rchild);
}
}
int bitree::yznum(binode *bt)
{
if(bt==NULL)
return 0;
else if(bt->lchild==NULL&&bt->rchild==NULL)
{
return 1;
}
else{
return yznum(bt->lchild)+yznum(bt->rchild);
}
}
int bitree::depth(binode*bt)
{
if(bt==NULL)
return 0;
else{
return max(depth(bt->lchild),depth(bt->rchild))+1;
}
}
int bitree::num(binode *bt)
{
if(bt==NULL)
return 0;
else{
return num(bt->lchild)+num(bt->rchild)+1;
}
}
binode *bitree::creat(binode *bt)
{
char ch;
cin>>ch;
if(ch=='#')
{
bt=NULL;
}
else{
bt=new binode;
bt->data=ch;
bt->lchild=creat(bt->lchild);
bt->rchild=creat(bt->rchild);
}
return bt;
}
void bitree::release(binode *bt)
{
if(bt==NULL){return ;}
else
{
release(bt->lchild);
release(bt->rchild);
delete bt;
}
}
void bitree::preorder(binode *bt)
{
if(bt==NULL)
{
return ;
}
else{
cout<<bt->data;
preorder(bt->lchild);
preorder(bt->rchild);
}
}
void bitree::inorder(binode *bt)
{
if(bt==NULL)
{
return ;
}
else{
preorder(bt->lchild);
cout<<bt->data;
preorder(bt->rchild);
}
}
void bitree::postorder(binode *bt)
{
if(bt==NULL)
{
return ;
}
else{
preorder(bt->lchild);
preorder(bt->rchild);
cout<<bt->data;
}
}
int main()
{ ios::sync_with_stdio(0);
bitree a;
/*a.preorder();
cout<<endl;
a.inorder();
cout<<endl;
a.postorder();
cout<<endl;*/
cout<<a.num();
cout<<endl;
cout<<a.yznum();
cout<<endl;
cout<<a.depth();
cout<<endl;
a.ex();
a.preorder();
cout<<endl;
char cc;
while(cin>>cc)
{
if(cc=='Y')
{
bitree b;
cout<<b.num();
cout<<endl;
cout<<b.yznum();
cout<<endl;
cout<<b.depth();
cout<<endl;
b.ex();
b.preorder();
cout<<endl;
}
else{
break;
}
}
return 0;
}
数据结构-二叉树的基本操作
最新推荐文章于 2024-04-25 10:20:25 发布