遍历函数中的树类

时间:2013-12-12 20:58:07

标签: c++

我有一个树类 - 请参阅下面的内容 - 我想遍历并从树类的外部函数中进行一些处理。为了遍历树,我需要设置一个指向树根的指针。 但是,由于它是私有的,我无法访问类外的根。

有没有办法优雅地没有使用getter - 检索根地址 - 没有使root公开?

感谢您的帮助。

template <class Key> class IntervalST
{
private:
    Interval<Key> *root;

    bool isRed(Interval<Key> *interval);
    Interval<Key> *rotateLeft(Interval<Key> *h);
    Interval<Key> *rotateRight(Interval<Key> *h);
    Interval<Key> *put(Interval<Key> *h,Key lo, Key hi, Key val);
    Interval<Key> *moveRedLeft(Interval<Key> *h);
    Interval<Key> *moveRedRight(Interval<Key> *h);
    Interval<Key> *deleteMin(Interval<Key> *h, Key hi);
    Interval<Key> *balance(Interval<Key> *h);
    Interval<Key> *remove(Interval<Key> *h, Key lo, Key hi);
    Interval<Key> *min(Interval<Key> *h);
    Interval<Key> *addDuplicate(Interval<Key> *h, Key hi);
    Interval<Key> *removeDuplicate(Interval<Key> *h, Key low, Key hi);
    Interval<Key> *getPointerToKey(Key low);

    void flipColors(Interval<Key> *h);
    void destroy(Interval<Key> *h);
    void printTree(Interval<Key> *h, int indent);
    Key maxVal(Interval<Key> *h);
    int size(Interval<Key> *h);
    bool isBST(Interval<Key> *x, Key min, Key max);
    inline bool isBST(){return isBST(root,0,0);}
    bool isSizeConsistent(Interval<Key> *x);
    inline bool isSizeConsistent(){return isSizeConsistent(root);}
    bool is23(Interval<Key> *x);
    inline bool is23(){return is23(root);}
    bool isBalanced();
    bool isBalanced(Interval<Key> *x,int black);
    int getKeySize(Key low);
    int compare(Key a, Key b);

public:

    //don't forget to build the constructor
    //and overload the =equal operator
    IntervalST():root(NULL){};
    ~IntervalST();
    void remove(Key lo, Key hi);
    void put(Key lo, Key hi);
    inline int size(){return size(root);}
    inline bool isEmpty(){return root == NULL;}
    void print(int indent = 0);
    void check();

};

2 个答案:

答案 0 :(得分:3)

你想要的是你班级的迭代器。它很可能被定义为朋友,因此它可以看到内部。否则,您需要公开访问方法。

Defining iterator of my own container了解详情。

答案 1 :(得分:3)

您可以添加接受树类的函数指针的方法,以便您可以向它传递一个将在树的每个节点上执行的仿函数。这使得遍历封装在树中,同时允许将指针传递给在每个节点上执行的任何函数。

像这样:

void IntervalST::executeOnEachNode(void (*functor)(Interval<Key> node,void* userData),
                                   void *userData = 0)
{
      Interval<Key> node;

      //Loop to traverse your tree stepping through each node
     {
       //Calls functor with supplied user data on specific node ( 
       functor(node,userData);
     }
}

其中functor是指向函数的指针,该函数接受一个参数(void *) - userData,如果需要,可以用于将捆绑的附加参数传递给函数。

用例(计算所有树节点):

void countAllNodes(Interval<Key> node,void* additionalIntArgument)
{
    int* count = static_cast<int*>(additionalIntArgument);
    *count += 1;
}

IntervalST<double> tree;

int count(0);
tree.executeOnEachNode(countAllNodes,reinterpret_cast<void*>(&count));
std::cout << "Tree has "<<count << " nodes "<<std::endl;