实验5:树和二叉树

来源:互联网 发布:相貌评分软件 编辑:程序博客网 时间:2024/06/11 14:31

一、实验目的

1、   熟练理解树和二叉树的相关概念,掌握的存储结构和相关操作实现;

2、   掌握树的顺序结构的实现;

3、   学会运用树的知识解决实际问题

二、 实验内容

自己确定一个二叉树(树结点类型、数目和结构自定)利用顺序结构方法存储。实现树的构造,并完成:

1)层序输出结点数据;

2)以合理的格式,输出各个结点和双亲、孩子结点信息;

3)输出所有的叶子结点信息;

4)分析你的算法对于给定的二叉树的存储效率。

三、实验步骤

1、依据实验内容,先确定具体的二叉树,并说明结点的数据据类型;

2、设计具体的算法;

3、写出完整程序;

4、总结、运行结果和分析算法效率。

5、总体收获和不足,疑问等。

四、实验要求

1、   按照数据结构实验任务书,提前做好实验预习与准备工作。

2、   在个人主页上发文章提交作业。

3、   实验课会抽查3-5人,希望你可以被查到!




源代码:


#include<stdlib.h> 

#include<iostream>    
#include<iomanip>  
using namespace std;    
static int Seqtree[20];  
static int num;  


class Seqtree
{
public:
Seqtree();
void Input(int a[],int n);
void Leverorder();
void Parentchild();
void Leaf();
private:
char data[20];
};


void Input(int a[],int n)
{  
    for(int i = 0;i<n;i++)
{  
        Seqtree[i] = a[i];  
    }  
    num = n;  
}  




void Leverorder(){  
    cout<<"层序遍历:";  
    for(int i=0; i<num; i++)  
    {  
        if(Seqtree[i] != 0)  
        {  
        cout<<setw(5)<<Seqtree[i];  
        }  
    };  
    cout<<endl;  
}  




void Parentchild()
{  
for(int i=1; i < num+1; i++)  
    {   
    if(Seqtree[i-1] != 0)  
    {  
        cout<<"结点"<<i<<": "<<Seqtree[i-1];  
        if(i!=1 && Seqtree[i/2-1])  
        {  
            cout<<setw(20)<<"其双亲结点: "<<Seqtree[i/2-1];  
        }  
        int m =2*i;  
        if(m<num && Seqtree[m-1] != 0)  
        {  
            cout<<setw(20)<<"其左孩子结点: "<<Seqtree[m-1];  
        }  
        if(m+1<num && Seqtree[m] != 0)  
        {  
            cout<<setw(20)<<"其右孩子结点: "<<Seqtree[m];  
        }  
        cout<<endl;  
    }  
    }  
}  




void Leaf(){  
    cout<<"叶子结点有:";  
    for(int i=0;i<num;i++)  
    {  
        int n = 2*(i+1);  
        if(n < num+1)  
        {  
           if(Seqtree[n-1] == 0 && Seqtree[n] == 0 && Seqtree[i]!=0)  
           {  
            cout<<setw(5)<<Seqtree[i];  
           };  
        }else{  
            if(Seqtree[i] !=0)  
            {  
                cout<<setw(5)<<Seqtree[i];  
            };  
        };  
    }  
    cout<<endl;  
}  




void main(){  
    int a[]={1,2,3,4,5};  
    Input(a,5);
cout<<'\n'<<endl;
    Leverorder();
cout<<'\n'<<endl;
    Parentchild();
cout<<'\n'<<endl;
    Leaf(); 
cout<<'\n'<<endl;
system("pause");

}  



实验总结:

回归算法本身可能会让思路更明了。

原创粉丝点击