目录:
这篇博客是对于红黑树内部迭代器实现, 点击红黑树的具体代码 .
一. 封装迭代器
对于红黑树迭代器的实现,我们就是要利用二叉树的指向来依次的遍历对应的节点来实现红黑树的迭代器,所存在的_header节点就是方便迭代器的实现
template<class V>
struct RBTreeIterator{
//泛型创建对应的结构
typedef RBNode<V> Node;
typedef RBTreeIterator<V> Self;
Node* _node;
RBTreeIterator(Node* node) //构造函数
:_node(node)
{
}
//解引用:*,->
V& operator*(){
//解引用直接指向对应的值
return _node->_val;
}
V* operator->(){
//指针指向也是一样的
return &_node->_val;
}
bool operator!=(const Self& it){
//!=的判断就是对于对应的node的判断
return _node != it._node;
}
//中序遍历
Self& operator++(){
//中序遍历就需要先遍历左子树,再根节点,最后再右子树
if (_node->_right){
//对每一个存在的子树进行遍历的操作
//右子树的最左节点
_node = _node->_right;
while (_node->_left){
_node = _node->_left;
}
}
else{
Node* parent = _node->_parent;
while (_node == parent