#ifndef Tree_H
#define Tree_H
const int MaxSize=100;
class Tree
{
public:
Tree(){length=0;}
void CreateTree(); //建立二叉树函数
void Message(int x); //按位查找结点信息
void Leaves(); //叶子结点
void LeverOrder(); //层序输出
private:
char a[MaxSize];
int length;
};
#endif
#include<iostream>
#include "Tree.h"
using namespace std;
void Tree::CreateTree() //建立二叉树函数
{
int i=1;
char ch;
cout<<"\t\t\t输入'#'表示结点为空,输入'0'表示停止输入!";
cout<<"\t\t\t输入二叉树的数据:";
while(1)
{
cin>>ch;
if(ch=='0') {cout<<endl<<"\t\t\t该二叉树建立成功!"<<endl;break;}
else a[i++]=ch;length++;
}
}
void Tree::Message(int i) //按位查找结点信息
{
int t;
while(t)
{
cout<<"\t\t\t请输入数字(1-"<<length<<")查找结点:";
cin>>i;
if(a[i]=='#'||i>length) cout<<"\t\t\t该结点不存在!";
else
{
cout<<"该结点信息:"<<a[i]<<endl;
cout<<"\t\t\t该结点的双亲结点信息:"<<a[i/2]<<endl;
if(a[2*i]=='#'||(2*i)>length)
cout<<"\t\t\t该结点无左孩子!"<<endl;
else cout<<"\t\t\t该结点的左孩子结点信息:"<<a[2*i]<<endl;
if(a[2*i+1]=='#'||(2*i+1)>length)
cout<<"\t\t\t该结点无右孩子!"<<endl;
else cout<<"\t\t\t该结点的右孩子结点信息:"<<a[2*i+1]<<endl;
}
cout<<"\t\t\t是否继续查找(1/0):";
cin>>t;
cout<<endl;
}
void Tree::Leaves()
{
if(a[1]!='0')
{
cout<<"\t\t\t叶子结点为:";
for(int i=1;i<=length;i++)
{
if((a[2*i]=='#'&&a[2*i+1]=='#')||((2*i+1)>length&&(2*i)>length)&&a[i]!='#')
cout<<a[i]<<" ";
}
cout<<endl;
}
else cout<<"\t\t\t该树为空!";
}
void Tree::LeverOrder() 层序输出
{
if(a[1]!='0')
{
for(int i=1;i<=length;i++)
cout<<" "<<a[i];
}
else cout<<"\t\t\t该树为空!";
}
#include<iostream>
#include "Tree.h"
using namespace std;
int main()
{
Tree tree;
cout<<endl<<"\t\t\t二叉树顺序存储的实现"<<endl<<endl;
cout<<"\t\t\t建立二叉树"<<endl;
tree.CreateTree(); //建立树
cout<<"\t\t\t请输入想要查找的结点信息"<<endl;
int x;
tree.Message(x); //按位查找
cout<<"\t\t\t该结点的叶子结点为"<<endl;
tree.Leaves(); //叶子结点
cout<<"\t\t\t层序输出该二叉树"<<endl;
cout<<"\t\t\t各结点信息:"; //层序输出
tree.LeverOrder();
cout<<endl;
cout<<"\t\t\t";
return0;
}