## 二叉树顺序结构存储

[cpp] view plain copy
#include<iostream>
#include<cstring>
using namespace std;
const int maxsize=100;
class bitree
{
public:
bitree();
~bitree(){}
int create_bt();
void leverorder();
void print();
void printleaf();
int tree[maxsize];
int count;
int num;
};

bitree::bitree()
{
for(int i=0;i<maxsize;i++)
tree[i]=-1;
count=0;
}
int bitree::create_bt()
{
int n,i=1;
num=0;
count=0;
cout<<"请按照从上到下、从左到右的顺序依次输入二叉树各个结点，结节点用0表示，以-1表示输入结束："<<endl;
while(cin>>n&&n!=-1&&i<maxsize)
{
tree[i]=n;
i++;
num++;
if(n==0) continue;
else count++;
}
return 0;
}
void bitree::leverorder()
{
if(tree[1]==-1) throw"该树为空树";
for(int i=1;tree[i]!=-1&&i<100;i++)
cout<<tree[i]<<" ";
cout<<"二叉树的层序遍历：";
for(i=1;tree[i]!=-1&&i<maxsize;i++)
{
if(tree[i]==0) continue;
cout<<tree[i]<<" ";
}
}
void bitree::print()
{
for(int i=1;tree[i]!=-1&&i<maxsize;i++)
{
static int j=0;
if(tree[i]==0) continue;
else j++;
cout<<"第"<<j<<"个结点信息为"<<tree[i]<<"   ";
if(tree[2*i]==0||tree[2*i]==-1) cout<<"该结点无左孩子"<<"    ";
else cout<<"左孩子为 "<<tree[2*i]<<"   ";
if(tree[2*i+1]==0||tree[2*i+1]==-1) cout<<"该结点无右孩子"<<"    ";
else cout<<"右孩子为 "<<tree[2*i+1]<<"   ";
if(int(i/2)==0) cout<<"该结点为根结点，无双亲"<<endl;
else if(tree[int(i/2)]==0) cout<<"该结点的双亲为 "<<tree[int(i/2)+1]<<endl;
else cout<<"该结点的双亲为 "<<tree[int(i/2)]<<endl;
}
}
void bitree::printleaf()
{
cout<<"所有的叶子结点信息为 ";
for(int i=1;i<num+1;i++)
{
if((tree[2*i]==0||tree[2*i]==-1)&&(tree[2*i+1]==0||tree[2*i+1]==-1))
if(tree[i]!=0&&tree[i]!=-1)
cout<<tree[i]<<"   ";
}
}

void main()
{
bitree b;
b.create_bt();
cout<<"输入的树为";
try
{
b.leverorder();
cout<<endl;
}
catch(char *s)
{
cout<<s<<endl;
}
cout<<"共有"<<b.count<<"个有效结点"<<endl;
b.print();
b.printleaf();
}