加个遍历函数(在主函数里)
#include <iostream>using namespace std;
template <class T>
class TreeNode
{
private:
TreeNode<T> *left;
TreeNode<T> *right;
T data;
public:
TreeNode(const T& item,TreeNode<T> *lptr=NULL,TreeNode<T> *rptr=NULL);
TreeNode<T> * GetLeft(void) const;
TreeNode<T> * GetRight(void) const;
static TreeNode<T>* GetTreeNode(T item,TreeNode<T> *lptr=NULL,TreeNode<T> *rptr=NULL);
void FreeTreeNode(TreeNode<T> *p);
void PreOrder(TreeNode<T> *t,void visit(T& item));
void InOrder(TreeNode<T> *t,void visit (T& item));
void PostOrder(TreeNode<T> *t,void visit(T& item));
};
//实现类中的函数
template <class T>
TreeNode<T>::TreeNode(const T& item,TreeNode<T> *lptr,TreeNode<T> *rptr):data(item),left(lptr),right(rptr)
{}
template <class T>
TreeNode<T>* TreeNode<T>::GetLeft(void) const
{
return (*left);
}
template <class T>
TreeNode<T>* TreeNode<T>::GetRight(void) const
{
return (*right);
}
template <class T>
TreeNode<T>* TreeNode<T>::GetTreeNode(T item,TreeNode<T> *lptr,TreeNode<T> *rptr)
{
TreeNode<T> *p;
p=new TreeNode<T>(item,lptr,rptr);
if(p==NULL)
{
cout<<"memory allocation failure!";
exit(1);
}
return p;
}
template <class T>
void TreeNode<T>::FreeTreeNode(TreeNode<T> *p)
{
delete p;
}
//visit函数
template <class T>
void visit(T *c)
{
cout<<(*c)<<endl;;
}
//遍历部分
//A:先序
template<class T>
void TreeNode<T>::PreOrder(TreeNode<T> *t,void visit(T& item))
{
if(t!=NULL)
{
visit(t->data);
PreOrder(t->left(),visit);
PreOrder(t->right(),visit);
}
}
//B:中序
template<class T>
void TreeNode<T>::InOrder(TreeNode<T> *t,void visit (T& item))
{
if(t!=NULL)
{
InOrder(t->left(),visit);
visit(t->data);
InOrder(t->right(),visit);
}
}
//C:后序
template<class T>
void TreeNode<T>::PostOrder(TreeNode<T> *t,void visit(T& item))
{
if(t!=NULL)
{
PostOrder(t->left(),visit);
PostOrder(t->right(),visit);
visit(t->data);
}
}
class CItem
{
public:
int data;
CItem(int data)
{
this->data = data;
}
};
void main()
{
TreeNode<CItem> *p = TreeNode<CItem>::GetTreeNode( CItem(1), NULL, NULL);
}