数据结构(树的顺序存储)C++

        树的存储结构分为顺序存储和链式存储。顺序存储结构使用一组连续的地址连续的存储单元来存储数据元素,使用顺序存储时,要能反映出节点之间的逻辑关系,要按照一定规律安排数组单元。

        注意:顺序存储仅仅适合存储完全二叉树或满二叉树,一般的二叉树更适合采用链式存储结构。

接下来是代码实现:

        为了能存储各种数据,这里采用类模版来实现。首先创建一个Tree类。

template<class T>
class Tree{
private:
    int a[MAXSIZE];
    T data[MAXSIZE];
public:
    Tree(){a[MAXSIZE-1]={0},data[MAXSIZE-1]={0};}
    void CreatTree();
    void PrintTree();
};

接下来对成员函数进行实现:

template<class T>
void Tree<T>::CreatTree() {
    int i;
    for(i=0;i<MAXSIZE;i++){
            a[i]=i+1;
            cout<<"请输入节点"<<i+1<<"的数据:";
            cin>>data[i];
    }
}

template<class T>
void Tree<T>::PrintTree() {
    int i;
    for(i=0;i<MAXSIZE;i++){
            cout<<"节点数据:"<<data[i]<<",位置:"<<a[i]<<endl;
    }
}

最后创建一个Tree对象:

int main(){
    Tree<char> A;
    A.CreatTree();
    A.PrintTree();
    return 0;
}

以下是完整代码:

#include<iostream>

#define MAXSIZE 3
using namespace std;

template<class T>
class Tree{
private:
    int a[MAXSIZE];
    T data[MAXSIZE];
public:
    Tree(){a[MAXSIZE-1]={0},data[MAXSIZE-1]={0};}
    void CreatTree();
    void PrintTree();
};

template<class T>
void Tree<T>::CreatTree() {
    int i;
    for(i=0;i<MAXSIZE;i++){
            a[i]=i+1;
            cout<<"请输入节点"<<i+1<<"的数据:";
            cin>>data[i];
    }
}

template<class T>
void Tree<T>::PrintTree() {
    int i;
    for(i=0;i<MAXSIZE;i++){
            cout<<"节点数据:"<<data[i]<<",位置:"<<a[i]<<endl;
    }
}
int main(){
    Tree<char> A;
    A.CreatTree();
    A.PrintTree();
    return 0;
}

运行结果(示例):

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值