信管117223王健数据结构实验 4:树和二叉树的实验 1

实验 4:树和二叉树的实验 1

 

一、实验目的 

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

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

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

二、实验内容 

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

(1)层序输出结点数据;

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

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

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

三、实验步骤 

程序代码:

#include<iostream>  

using namespace std;    

const int MaxSize=100; //树最大规模为100   

class Tree    

{    

private:    

    char data[MaxSize]; //用数组存放数据   

    int length;  //记录树大小  

public:    

    Tree(char a[],int n);  //有参构造函数  

    ~Tree(){}    

    void Leveroder();  //层序输出      

    void ParentChild();  //输出结点的双亲、孩子信息    

    void Leaf();  //输出叶子信息    

};

 

    

Tree::Tree(char a[],int n)    

{    

    if(n<1||n>MaxSize) throw"错误";   

    for(int i=0;i<n;i++)    //实现数据的存储  

        data[i]=a[i];    

    length=n;    

}

 

  

void Tree::Leveroder()    

{    

    for(int i=0;i<length;i++)    

    {    

        if(data[i]!='#')   //当"#"(虚结点)时,表示无数据,为空  

            cout<<data[i];    

    }    

}

 

   

void Tree::ParentChild()     

{    

    int b,c1,c2;    

    for(int i=1;i<=length;i++)    

    {    

        c1=2*i;  //左孩子    

        c2=2*i+1; //右孩子    

        b=i/2;  //双亲    

        if(data[i-1]!='#')    

        {    

            if(b>=1)    

                cout<<"结点"<<i<<"双亲为:"<<data[b-1]<<"   ";    

            else    

                cout<<"结点"<<i<<"无双亲"<<"   ";    

            if(data[c1-1]!='#'&&c1<=length)   //最后一层叶子结点无孩子   

                cout<<"左孩子为:"<<data[c1-1]<<"   ";    

            else    

                cout<<"无左孩子"<<"   ";    

            if(data[c2-1]!='#'&&c2<=length)    

                cout<<"右孩子为:"<<data[c2-1]<<"   ";    

            else    

                cout<<"无右孩子"<<"  ";    

            cout<<endl;    

        }    

    }    

}

 

   

void Tree::Leaf()    

{    

    int c1,c2;    

    for(int i=1;i<=length;i++)    

    {    

        c1=2*i;    

        c2=2*i+1;     

        if(data[c1-1]=='#' && data[c2-1]=='#' && data[i-1]!='#')  //最后一层叶子没有孩子且该结点不为空  

            cout<<data[i-1];    

        if(c1>length && data[i-1]!='#')    

            cout<<data[i-1];    

    }    

}

 

   

int main()    

{    

    char b[9]={'A','B','C','D','#','E','F','#','G'};    

    Tree c(b,9);    

    cout<<"该二叉树的层序输出为:";    

    c.Leveroder();    

    cout<<endl;     

    c.ParentChild();    

    cout<<endl;    

    cout<<"叶子结点信息为:";    

    c.Leaf();    

    cout<<endl;

return 0;

}    

运行结果:

 

猜你喜欢

转载自blog.csdn.net/Smart_J_King/article/details/80216089