树的存储结构分为顺序存储和链式存储。顺序存储结构使用一组连续的地址连续的存储单元来存储数据元素,使用顺序存储时,要能反映出节点之间的逻辑关系,要按照一定规律安排数组单元。
注意:顺序存储仅仅适合存储完全二叉树或满二叉树,一般的二叉树更适合采用链式存储结构。
接下来是代码实现:
为了能存储各种数据,这里采用类模版来实现。首先创建一个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;
}
运行结果(示例):