<span style="color:#3333ff;"><span style="font-size:14px;">#include <iostream>
using namespace std;
template<typename Elemtype>
struct treeNode
{
Elemtype data;
treeNode<Elemtype> *left,*right;
};
template<typename Elemtype>
class BTree
{
public:
treeNode<Elemtype> *rootnode;
public:
//void template();
void Insert(treeNode<Elemtype>** parentNode,treeNode<Elemtype> *node);
/*
*<function 创建树/>
*<@para1 data>数据集合</para1>
*<@para2 len>长度</para2>
*/
void Creat(Elemtype data[],int len );
void PreOrder(treeNode<Elemtype>* currentnode); //前序遍历
void MidOrder(treeNode<Elemtype>* currentnode); //中序遍历
void PosOrder(treeNode<Elemtype>* currentnode); //后续遍历
void Print(); //打印
protected:
private:
};
template<typename Elemtype>
void BTree<Elemtype>::Insert(treeNode<Elemtype>** parentNode,treeNode<Elemtype> *node)
{
if (*parentNode==NULL)
{
*parentNode=node;
}
else if (node->data==(*parentNode)->data)
{
return;
}
else if (node->data<(*parentNode)->data)
{
Insert(&((*parentNode)->left),node);
}
else
{
Insert(&((*parentNode)->right),node);
}
}
template<typename Elemtype>
void BTree<Elemtype>::Creat(Elemtype data[],int len )
{
treeNode<Elemtype> *p;
rootnode=NULL;
for (int i=0;i<len;i++)
{
p=new treeNode<Elemtype>();
p->data=data[i];
p->left=NULL;
p->right=NULL;
Insert(&rootnode,p);
}
}
template<typename Elemtype>
void BTree<Elemtype>::PreOrder(treeNode<Elemtype>* currentnode)
{
if (currentnode!=NULL)
{
cout<<currentnode->data<<endl;
PreOrder(currentnode->left);
PreOrder(currentnode->right);
}
}
template<typename Elemtype>
void BTree<Elemtype>::MidOrder(treeNode<Elemtype>* currentnode)
{
if (currentnode!=NULL)
{
PreOrder(currentnode->left);
cout<<currentnode->data<<endl;
PreOrder(currentnode->right);
}
}
template<typename Elemtype>
void BTree<Elemtype>::PosOrder(treeNode<Elemtype>* currentnode)
{
if (currentnode!=NULL)
{
PreOrder(currentnode->left);
PreOrder(currentnode->right);
cout<<currentnode->data<<endl;
}
}
template<typename Elemtype>
void BTree<Elemtype>::Print()
{
cout<<"前序输出"<<endl;
PreOrder(rootnode);
cout<<"中序输出"<<endl;
MidOrder(rootnode);
cout<<"后序输出"<<endl;
PosOrder(rootnode);
}</span></span><pre class="cpp" name="code"><span style="font-size:14px;">#include "SortTree.h"
#include "stdlib.h"
int main()
{
BTree<int>* tree=new BTree<int>();
int arr[5]={2,3,5,0,1};
tree->Creat(arr,5);
tree->Print();
system("pause");
}</span>