Balance Search tree--red and black tree Rbtree

Source: Internet
Author: User

The red and black Tree is a two-fork search tree , which adds a storage bit on each node to represent the color of the node, which can be red or Black.

By constraining the height of the tree by any color from the root to the leaf node's simple path, the red-black tree guarantees that the longest path does not exceed twice times the shortest path , thus approximating the balance.

The red-black tree is a two-fork search tree that satisfies the following red-black nature:

1. Each node, not red or black

2. The root node is black

3. If a node is red, its two child nodes are black (there is no contiguous red node)

4. For each node, the same number of black nodes are included on the simple path from the node to all of its descendant leaf nodes.

Think : Why the above color constraints, red and black trees can guarantee that the longest path does not exceed the shortest path twice times?

The color of the nodes on the shortest path is all black, and the longest path is the path of black crossing, which has the same number of black nodes and red nodes as the shortest path. So the longest path of red and black trees that we have built according to the nature of the red and black trees must not exceed the shortest path twice!

Create a red-black tree node class:

The new node that is inserted is red by default. The reason is: inserting a black node will inevitably affect all paths contain the same number of black nodes this principle, more difficult to maintain!

Enum Color{red,black};template<class k,class v>struct rbtreenode{k _key; V _value; Color _color;//rbtreenode<k, v>* _left;//pointing to the left child's pointer rbtreenode<k, v>* _right;//pointing right child's pointer rbtreenode<k, V >* _parent;//Pointer to parent node Rbtreenode (const k& key=k (), const V&VALUE=V ()): _key (Key), _value (value), _color (RED) , _left (null), _right (null), _parent (null) {}};

 Red and black trees need to change color or use rotation to reduce the height of several cases:

Figure Note: G stands for grandfather grandfather node; p for parent Father node; u for Uncle Uncle; Cur represents the current node

One, the parent node is the left child of the grandfather node

The color of 1.uncle is red

① current node cur is the left child of the parent

② current node cur is the right child of the parent

The color of 2.uncle is black or uncle is null

①cur is the left child of the parent, right single-spin

②cur is the right child of the parent, first left and right double-spin

Second, the parent node is the right child of the grandfather node

The color of 1.uncle is red

①cur is the right child of the parent.

②cur is the left child of the parent.

The color of 2.uncle is black or uncle is null

①cur is the right child of the parent.

②cur is the left child of the parent.

To insert a node:

    1. First, to find the location where the node was inserted, insert the node when it is found
    2. Then, check the legality of the color of the nodes of the red and black tree, and change color or rotation according to the result of inspection.

Based on the above scenario, the red-black tree uses the Insert function algorithm encapsulated in the template class to complete:

Template<class K, Class V>bool rbtree<k, V>::insert (const k& key, const v& value) {if (_root = = NULL) {_ root = new rbtreenode<k, v> (key, value); _root->_color = Black;return true;} Find location rbtreenode<k, v>* cur = _root; Rbtreenode<k, v>* parent = null;while (cur) {if (Cur->_key > key) {parent = Cur;cur = Cur->_left;} else if (Cur->_key < key) {parent = Cur;cur = Cur->_right;} Else{return false;}}  Insert cur = new rbtreenode<k, v> (key, value); cur->_parent = Parent;if (Parent->_key > key) Parent->_left = Cur;else if (Parent->_key < key) Parent->_right = cur;//Checks if the color assignment meets the requirements while (parent&&parent->_color= =red) {rbtreenode<k, v>* grandfather = parent->_parent;if (parent = = Grandfather->_left) {RBTreeNode<K, V >* Uncle = grandfather->_right;if (Uncle&&uncle->_color = = red) {//first case discoloration Grandfather->_color = red ;p Arent->_color =black;uncle->_color = black;cur = Grandfather;parent =Grandfather->_parent;} else if ((uncle&&uncle->_color==black) | | | Uncle==null) {if (cur = = parent->_left) {//second case Right paddle cur must have black child Parent->_color = Black;grandfather->_color = RED; Rotater (grandfather);} else{//the third situation around the Rotatel (parent);p Arent->_color = Black;grandfather->_color = RED; Rotater (grandfather);} Break;}} else if (parent = = Grandfather->_right) {rbtreenode<k, v>* uncle = grandfather->_left;if (uncle&& Uncle->_color = = RED) {//first case discoloration Grandfather->_color = Red;parent->_color = Black;uncle->_color = BLACK;cur = Grandfather;parent = cur->_parent;} else if ((Uncle&&uncle->_color = = BLACK) | | Uncle==null) {///second case Zodan cur must have black child if (cur = = parent->_right) {Parent->_color = Black;grandfather->_color = RED; Rotatel (grandfather);} else if (cur==parent->_left) {//third case right-left double-rotater (parent);p Arent->_color = Black;grandfather->_color = RED; Rotatel (grandfather);} Break;}}} _root->_color = Black;return true;}

After inserting, we can not intuitively see whether the color of the red and black tree nodes is legal, nor can we visually see whether the number of black nodes in each path is the same.

Therefore, two functions are implemented here to facilitate the verification of the legitimacy of red and black trees.

    • Red black tree Each path has the same number of black nodes, so wander through a path and calculate the number of black nodes on the road. Use this data as a benchmark and compare the number of black nodes in other paths to determine if they are all the same.
    • If the current node is red and it has a parent node, then determine if the parent node's color is also red, so that it can be judged whether the tree satisfies the nature of two consecutive nodes cannot be red at the same time .
Verification of the legality of red and black trees Template<class K, class V>bool rbtree<k, V>::check () {//Statistics red black Tree The number of black nodes on each path int blacknum = 0; Rbtreenode<k, v>* cur = _root;while (cur) {if (Cur->_color = BLACK) blacknum++;cur = Cur->_left;} int cbnum = 0;return _check (_root,blacknum,cbnum);} Recursive auxiliary template<class K, class V>bool rbtree<k, V>::_check (rbtreenode<k, v>* root, int blacknum, int cbnum) {if (root = NULL) return true;if (Root->_color = = BLACK) {cbnum++;if (Root->_left = Null&amp &root->_right = = NULL) {//go to the leaf node to compare the number of black nodes on this path with the number of black nodes previously counted if (Blacknum = = Cbnum) {return true;} Else{cout << "leaf node is << root->_key <<" The number of black nodes in the path is not equal to the number of black nodes in the leftmost branch! "<< Endl;return false;}}} else if (Root->_parent&&root->_parent->_color = = red) {//Determine if there is a contiguous two red nodes cout << root->_ Parent->_key << "and" << Root->_key << "for two consecutive red nodes" << Endl;return false;} Recursive test path return _check (Root->_left, Blacknum, CBnum) && _check (Root->_right, Blacknum, cbnum);} 

  Comparison of red and black trees and AVL trees

Red and black trees and AVL trees are efficient balanced binary tree, adding and removing the time complexity of the search and change is O (LG (N)) Red black tree does not pursue complete balance, to ensure that the longest path does not exceed the shortest path of twice times, relatively, reduce the rotation requirements, so the performance will be better than the AVL tree, so the actual use of

Balance Search tree--red and black tree Rbtree

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.