1. 程式人生 > >二叉樹順序結構

二叉樹順序結構

試驗內容:

自己確定一個二叉樹(樹結點型別、數目和結構自定)利用順序結構方法儲存。實現樹的構造,並完成:

1) 層序輸出結點資料;

2) 以合理的格式,輸出各個結點和雙親、孩子結點資訊;

3) 輸出所有的葉子結點資訊;

4)分析你的演算法對於給定的二叉樹的儲存效率。

#include<iostream>
#include<string>
#include<math.h>
using namespace std;
class Tree{
private:
char data[100];
int n;
public:
Tree();
void insert(char x);
void seq();
void last();
void parents(char x);
void child(char x);
};
Tree::Tree(){
n=0;
}
void Tree::insert(char x){
n++;
data[n]=x;
}
void Tree::seq(){
cout<<"所得二叉樹為:"<<endl;
int y=1;
for(int i=1;i<=n;i++){
if(i==pow(2,y)){
y++;
cout<<endl;
}
cout<<data[i];
}
cout<<endl;
}
void Tree::last(){
int y=0;
while(pow(2,y)<n){
y++;
}
y=y-1;
for(int i=pow(2,y);i<=n;i++){
cout<<data[i];
}
}
void Tree::parents(char x){
int i=1;
while(data[i]!=x && i>=100){
i++;
}
cout<<"雙親為:"<<data[i]<<endl;
}
void Tree::child(char x){
int i=1;
while(data[i]!=x && i>=100){
i++;
}
if(data[2*i]==NULL || data[2*i]=='*'){
cout<<"沒有左孩子"<<endl;
}else{
cout<<"左孩子是:"<<data[2*i]<<endl;
}
if(data[2*i+1]==NULL || data[2*i+1]=='*'){
cout<<"沒有右孩子"<<endl;
}else{
cout<<"右孩子是:"<<data[2*i+1]<<endl;
}
}
void main()
{
string a;
while(cin>>a)
{
Tree tree;
for(int i=0;i<a.length();i++)
{
tree.insert(a[i]);
}
tree.seq();
cout<<"葉子為:";
tree.last();
cout<<endl;
char x;
cout<<"請輸入x,查詢它的雙親和孩子"<<endl;
cin>>x;
tree.parents(x);
tree.child(x);


}
}