标题:加个遍历函数(在主函数里)
只看楼主
张信哲
Rank: 1
等 级:新手上路
帖 子:139
专家分:0
注 册:2008-4-3
 问题点数:0 回复次数:1 
加个遍历函数(在主函数里)
#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);
}
搜索更多相关主题的帖子: TreeNode 遍历 void 函数 NULL 
2008-05-12 17:04
张信哲
Rank: 1
等 级:新手上路
帖 子:139
专家分:0
注 册:2008-4-3
得分:0 
帮帮我啊

相信自己,学无止尽。
2008-05-14 20:29



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-213931-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.925655 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved