# 实验四

#include<iostream>
using namespace std;
const int MaxSize=100;

class BiTree
{
public:
BiTree(char a[],int n);
~BiTree(){}
void Print1();
void Print2();
void Print3();
private:
char data[MaxSize];
int length;
};

BiTree::BiTree(char a[],int n)
{
if(n>MaxSize||n<1) throw "参数非法";
for(int i=0;i<n;i++)
data[i]=a[i];
length=n;
}

void BiTree::Print1()
{
cout<<"层序输出结点数据为:";
for(int i=0;i<length;i++)
if(data[i]!='\0') cout<<data[i]<<" ";
cout<<endl<<endl;
}

void BiTree::Print2()
{
for(int i=1;i<=length;i++)
{
int l=2*i;
int r=2*i+1;
int p=i/2;
if(data[i-1]!='\0')
{
cout<<"结点"<<i<<"为"<<data[i-1];
if(p>=1&&data[p-1]!='\0') cout<<",双亲为"<<data[p-1];
else cout<<",无双亲";
if(data[l-1]!='\0'&&l<length) cout<<",左孩子为"<<data[l-1];
else cout<<",无左孩子";
if(data[r-1]!='\0'&&r<length) cout<<",右孩子为"<<data[r-1];
else cout<<",无右孩子";
cout<<endl;
}
}
}

void BiTree::Print3()
{
cout<<endl<<"叶子结点:";
for(int i=1;i<=length;i++)
{
int l=2*i;
int r=2*i+1;
if(l>length&&data[i-1]!='\0') cout<<data[i-1]<<" ";
}
cout<<endl;
}

void main()
{
char a[7]={'A','B','\0','\0','C','\0','D'};
BiTree t(a,7);
t.Print1();
t.Print2();
t.Print3();
system("pause");
}

• 评论

• 上一篇
• 下一篇