关于二叉查找树的++迭代器的实现

class const_iterator
{
protected:
    BinaryNode<Comparable> *current;
public:
    const_iterator():current(NULL)
    {}

    const Comparable & operator*() const
    {
        return retrieve();
    }

    const_iterator & operator++()
    {
        BinaryNode<Comparable> *t;
        if(current->right)                         //如果现在这个节点的右子树有值,即有比这个节点大的值
        {
            t=current->right;                      //把这个比它值大的节点赋给t
            while(t->left!=NULL)                   //只要这个节点的左子树存在,即存在比current节点大但又是这些值中偏小的节点
                t=t->left;                         //用while找到比它大的里面最小的节点
            current=t;                             //把这个节点赋给current
        }
        else                                       //如果不存在这个节点的右子树,即有比这个节点大的值
        {                           
            t=current->parent;                          //那么向上寻找,找他的父节点,他的父节点的值可能会比它大
            cout<<"first parent is "<<t->element<<endl;
            while(t&&t->element < current->element)      //一直往上找,直到他的父节点的值比它大,那么退出循环
                t=t->parent;
            current=t;                                   //把找到的这个节点赋给current
        }
        return *this;
    }
const_iterator operator++ (int)
{
    const_iterator old=*this;
    ++(*this);
    return old;
}

bool operator==(const_iterator &rhs) const
{
    return current==rhs.current;
}

bool operator!=(const_iterator &rhs) const
{
    return !(*this==rhs);
}

protected:
    Comparable &retrieve() const
    {
        return current->element;
    }

    const_iterator(BinaryNode<Comparable> *p): current(p)
    {}

    friend class Set;



};
//可想而知,先找子节点的最大值中最小的一个,设为n1;如若没有,则找父节点中离它最近的比它大的节点,设为n2;且n1一定小于n2.
//因为n1一定是n2左子树那一系中的节点,所以先往下找,实在没有,再往上找。

//This is the public insert
iterator insert(const Comparable &x)
{
Size++;
return insert(x,root,root);
}


//This is private
iterator insert(const Comparable &x,BinaryNode<Comparable> *&t,BinaryNode<Comparable> *p)
{
if(t==NULL)
{
t=new BinaryNode<Comparable>(x,NULL,NULL,p);
return iterator(t);
}
else if(x<t->element)
return(insert(x,t->left,t));
else if(x>t->element)
return(insert(x,t->right,t));
return iterator(t);
}


//This is the public begin
iterator begin()
{
BinaryNode<Comparable> *t=root;
while(t->left)
t=t->left;
return iterator(t);
}


template <typename Comparable>
struct BinaryNode
{
Comparable element;
BinaryNode *left;
BinaryNode *right;
BinaryNode *parent;


BinaryNode()
{
left=NULL;right=NULL;parent=NULL;
}
BinaryNode(const Comparable &theElement)
{
element=theElement;
left=NULL;
right=NULL;
parent=NULL;
}


BinaryNode(const Comparable &theElement,BinaryNode *lt,BinaryNode *rt,BinaryNode *pt):element(theElement),left(lt),right(rt),parent(pt)
{}
};

 
原文地址:https://www.cnblogs.com/CClarence/p/5158006.html