赞
踩
红黑树的概念:
- enum Colour
- {
- BLACK,
- RED
- };
-
-
- template<class K, class V>
- struct RBTreeNode
- {
- RBTreeNode<K, V>* _left;
- RBTreeNode<K, V>* _right;
- RBTreeNode<K, V>* _parent;
-
- Colour _col;
- pair<K, V> _kv;
-
- RBTreeNode(const pair<K, V>& kv)
- :_left(nullptr)
- , _right(nullptr)
- , _parent(nullptr)
- , _col(RED)
- , _kv(kv)
- {}
- };
插入节点:
红黑树插入节点会发生增加节点后破坏了红黑树的性质的情况,需要变更某些节点的颜色,有时还要通过旋转改变红黑树的结构才能达到保持性质的目的。
插入节点时,先根据二叉搜索树的性质由节点定义知,新增节点默认为红色,如果新节点的父节点为黑色,已经满足性质不需要调整,如果父节点为红色,出现了连续的红色节点,需要调整,当前节点的叔叔节点对调整方式有很大影响,读者可在下文体会到。
具体分为下边这几种处理方式:
定义:
cur 为当前节点
p为父节点
g为爷节点
u为叔节点
情况①:p,u为红,g为黑
p,u改为黑,g改为红,cur指向g,继续向上调整
情况②: p为红,g为黑,u不存在/u为黑 , p为g的左(右),cur为p的左(右)
u不存在时,cur为新增,以g为中心右(左)单旋 ,p,g都变色
u为黑时,cur不是新增,而是情况①变色导致的
情况③:p为红,g为黑,u不存在/u为黑 , p为g的左(右),cur为p的右(左)
以p为中心左(右)单旋,再执行情况②
最后要把根节点置为黑色,旋转的程序可参考这里
红黑树插入节点程序如下:
- bool Insert(const pair<K, V>& kv)
- {
- if (_root == nullptr)
- {
- _root = new Node(kv);
- _root->_col = BLACK;
- return true;
- }
-
- Node* parent = nullptr;
- Node* cur = _root;
- while (cur)
- {
- if (cur->_kv.first < kv.first)
- {
- parent = cur;
- cur = cur->_right;
- }
- else if (cur->_kv.first > kv.first)
- {
- parent = cur;
- cur = cur->_left;
- }
- else
- {
- return false;
- }
- }
-
- // 新增节点,颜色是红色,可能破坏规则3,产生连续红色节点
- cur = new Node(kv);
- cur->_col = RED;
-
- if (parent->_kv.first < kv.first)
- {
- parent->_right = cur;
- cur->_parent = parent;
- }
- else
- {
- parent->_left = cur;
- cur->_parent = parent;
- }
-
- // 控制近似平衡
- while (parent && parent->_col == RED)
- {
- Node* grandfather = parent->_parent;
- if (parent == grandfather->_left)
- {
- Node* uncle = grandfather->_right;
- // 情况一:uncle存在且为红,进行变色处理,并继续往上更新处理
- if (uncle && uncle->_col == RED)
- {
- parent->_col = uncle->_col = BLACK;
- grandfather->_col = RED;
-
- cur = grandfather;
- parent = cur->_parent;
- } // 情况二+三:uncle不存在,或者存在且为黑,需要旋转+变色处理
- else
- {
- // 情况二:单旋+变色
- if (cur == parent->_left)
- {
- RotateR(grandfather);
- parent->_col = BLACK;
- grandfather->_col = RED;
- }
- else // 情况三:双旋 + 变色
- {
- RotateL(parent);
- RotateR(grandfather);
- cur->_col = BLACK;
- grandfather->_col = RED;
- }
-
- break;
- }
- }
- else // (parent == grandfather->_right)
- {
- Node* uncle = grandfather->_left;
- if (uncle && uncle->_col == RED)
- {
- parent->_col = uncle->_col = BLACK;
- grandfather->_col = RED;
-
- cur = grandfather;
- parent = cur->_parent;
- }
- else
- {
- if (parent->_right == cur)
- {
- RotateL(grandfather);
- parent->_col = BLACK;
- grandfather->_col = RED;
- }
- else
- {
- RotateR(parent);
- RotateL(grandfather);
- cur->_col = BLACK;
- grandfather->_col = RED;
- }
-
- break;
- }
- }
- }
-
- _root->_col = BLACK;
- return true;
- }
红黑树和AVL树的比较:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。