Red and black Trees

Source: Internet
Author: User

First, the basic concept of red and black trees

The red-black tree is a self-balancing binary search tree. The typical use is to implement associative arrays, which are efficient in practice and have a time complexity of O (log). The main implementation of find, insert and delete features. Its statistical performance is higher than the balanced binary tree (AVL tree).

A red-black tree is a specific type of two-fork tree. It is used to organize data, such as a structure of a block of numbers, all of which are stored in nodes where one node always functions as the starting position, not the son of any node, the root node, or the root. A maximum of two "sons" are the other nodes to which it is connected. All these sons can have their own sons, and so on. So the root node has the path to connect it to any other node in the tree.

If a node has no son, we call it a leaf node, because intuitively it is on the edge of the tree. A subtree is a part of a tree that can be extended from a particular node and is itself treated as a tree. In a red-black tree, the leaves are assumed to be null or empty.

The red-black tree is a two-fork search tree. The comparison value of each node in it must be greater than or equal to all nodes in its left subtree, and is less than or equal to all nodes in its right sub-tree. This ensures that the red-black tree can quickly find the given value in the tree when it works.

Application:

In C + + STL, many parts (such as set,map) have applied red-black tree variants, and many virtual memory management in Linux has also applied red-black trees.

Properties:

1. The node is red or black.

2. The root node is black.

3. Each leaf node (empty node) is black.

4. You cannot have two contiguous red nodes on all paths.

5. All paths contain the same number of black nodes.

These constraints enforce the key nature of the red-black tree: The longest possible path is no greater than twice times the shortest path . So the tree is generally balanced.

Why these features ensure this key property: The shortest possible paths are black nodes, the longest possible paths have alternating red and black nodes, depending on the nature of 5 all the longest paths have the same number of black nodes, which indicates that no path can be more than twice times longer than any other path.

Ii. operation of red and black trees

A read-only operation on a red-black tree does not need to modify the operation used for the binary lookup tree, because it is also a binary lookup tree. However, after inserting and deleting, the red and black properties may not meet the requirements. Restoring the red-black attribute requires a small amount (O (log n)) of color changes (which is very fast in practice) and no more than three tree rotations (insert is two times). This allows insertions and deletions to remain O (log n) times, but it results in very complex operations.


Three, insert operation

Situation one: Uncle exists and is red

Turn the father and uncle Black, grandfather turns red, and if grandfather's father is red, he turns his grandfather into a newly inserted child and continues to change upward.

650) this.width=650; "src="/e/u261/themes/default/images/spacer.gif "style=" Background:url ("/e/u261/lang/zh-cn/ Images/localimage.png ") no-repeat center;border:1px solid #ddd;" alt= "Spacer.gif"/>650 "this.width=650;" src= "http ://s1.51cto.com/wyfs02/m00/84/74/wkiol1eqz4vtcl6naaaqgsn94r4994.png "title=" Uncle Red. png "alt=" Wkiol1eqz4vtcl6naaaqgsn94r4994.png "/>

Situation two: Uncle exists and for black or uncle does not exist (father for grandfather's left child, inserted for father's left child or both for right child)

All for the left child: right-handed grandfather axis, the grandfather turned red, the father turned black;

All for the right child: a grandfather turned the Axis left, his grandfather red and his father black.

650) this.width=650; "src="/e/u261/themes/default/images/spacer.gif "style=" Background:url ("/e/u261/lang/zh-cn/ Images/localimage.png ") no-repeat center;border:1px solid #ddd;" alt= "Spacer.gif"/>650 "this.width=650;" src= "http ://s2.51cto.com/wyfs02/m01/84/75/wkiom1eqz6daykucaaasfapax2a368.png "title=" Uncle Black 1.png "alt=" Wkiom1eqz6daykucaaasfapax2a368.png "/>

Situation three: Uncle exists and for black or uncle does not exist (father for grandfather's left child, inserted for Father's right child or vice versa)

The father is the left child, inserted for the right child: with the father as the axis left, the father and inserted children swap identities, into the second case (all left children);

The father is the right child, inserted for the left child: the father Axis right, the father and inserted children swap identities, into the second case (all Right children);

650) this.width=650; "src="/e/u261/themes/default/images/spacer.gif "style=" Background:url ("/e/u261/lang/zh-cn/ Images/localimage.png ") no-repeat center;border:1px solid #ddd;" alt= "Spacer.gif"/>650 "this.width=650;" src= "http ://s5.51cto.com/wyfs02/m01/84/74/wkiol1eqz7qjnzqfaaaweraiqhs076.png "title=" Uncle Black 2.png "alt=" Wkiol1eqz7qjnzqfaaaweraiqhs076.png "/>

Four, Code chestnut

#include <iostream>using namespace std;enum color{red,black};template<class k,  class V>struct RBTreeNode{K _key; v _value; rbtreenode<k, v>* _parent; rbtreenode<k, v>* _left; rbtreenode<k, v>* _right;color _col; Rbtreenode (Const k& key, const v& value)  :_key (key), _value (value), _ Parent (NULL), _left (null), _right (null), _col (RED) {}}; template<class k, class v>class  rbtree{typedef rbtreenode<k, v> node;private:node* _root;public:rbtree (): _root (NULL) {}void instert (K key, v value) {///does not have a node when creating and inserting a root node if (_root == null) {_root =  new node (key, value); _root->_col = black;return;} There would have been a node, find the right location, create the node and insert node* cur = _root; Node* parent = null;while (cur) {parent = cur;if (Cur->_key > key) {cur& NBsP;= cur->_left;if (cur == null) {parent->_left = new node (key, value); Cur = parent->_left;cur->_parent = parent;break;}} Else if (Cur->_key < key) {cur = cur->_right;if (Cur == NULL) {parent- >_right = new node (key, value); cur = parent->_right;cur->_parent =  parent;break;}}} _root->_col = black;//handles the color of the node while (Cur != _root && parent->_col  == red) {node* grandfather = parent->_parent;if (grandfather->_left ==  parent) {node* uncle = grandfather->_right;//1. Uncle exists and is red if (uncle &&  uncle->_col == red) {grandfather->_col = red;parent->_col = black;uncle- &GT;_COL&NBSP;=&NBSP;BLACK;CUR&NBSP;=&NBSP;GRANDFATHER;PARENT&NBSP;=&NBSP;CUR-&GT;_PARENT;&NBSP;}//2. Uncle doesn't exist or uncle exists and is black else{//     <if (cur == parent->_right) {Rotatel (parent); swap (cur, parent);}    /parent->_col = BLACK;grandfather->_col = RED; Rotater (grandfather); break;}} Grandfather->_right == parentelse{node*uncle = grandfather->_left;//1. Uncle exists and is red if ( uncle && uncle->_col == red) {Grandfather->_col = red;parent->_ Col = black;uncle->_col = black;cur = grandfather;parent = cur-> _parent;} 2. Uncle does not exist or uncle exists and is black else{//        >if (cur == parent->_ left) {rotater (parent); swap (parent, cur);}          /parent->_col = black;grandfather->_ col = red; Rotatel (grandfather); break;}}} _root->_col = black;} Bool isbalance () {int key = 0; Node* cur = _root;while (cur) {if (cur->_col  == black) key++;//calculates the black node of a path as the base value cur = cur->_left; }int count = 0; Return _isbalance (_root, key, count);} Void inorder () {_inorder (_root);} Private:void _inorder (node* root) {if (root == null) Return;_inorder (root->_left); cout  << root->_key <<  _inorder (root->_right);} Bool _isbalance (Node* root, const int k, int count) {if (root ==  NULL) return true;if (root->_col == black) count++;if (root->_col == red & & root->_parent->_col == red) {cout <<  "Continuous red"  << endl; Return false;} if (root->_left == null && root->_right == null &&  count != k) {cout <<  "Black number Unequal"  << endl;return false;} Return _isbalance (root->_left, k, cOunt)  && _isbalance (root->_right, k, count);} Void rotater (node* parent) {node* subl = parent->_left; node* sublr = subl->_right; node* ppnode = parent->_parent; Subl->_right = parent;parent->_parent = subl;parent->_left = sublr;if ( SUBLR) sublr->_parent = parent;if (ppnode == null) {_root = subl; Subl->_parent = null;} Else if (ppnode->_left == parent) {ppnode->_left = subl; Subl->_parent = ppnode;} else{ppnode->_right = subl; Subl->_parent = ppnode;}} Void rotatel (node* parent) {node* subr = parent->_right; node* subrl = subr->_left; node* ppnode = parent->_parent; Subr->_left = parent;parent->_parent = subr;parent->_right = subrl;if ( SUBRL) {Subrl->_parent = parent;} if (ppnode == null) {_root = subr; Subr->_parent = null;} Else if (ppnode->_left == parent) {ppnode->_left = subr; Subr->_parent = ppnode;} else{ppnode->_right = subr; subr->_parent = ppnode;}}}; Int main () {rbtree<int, int> t;int a[] = {1, 2, 3, 4, 5 ,  6, 7, 9, 8};for (int i = 0; i< (sizeof (a)/sizeof (a[0)); i++) {T. Instert (a[i],i); Cout << a[i] << t.isbalance ()  << endl;} T.inorder (); Cout << t.isbalance ()  << endl;system ("pause"); return 0;}


This article is from "GREEN" blog, please make sure to keep this source http://green906.blog.51cto.com/10697569/1828603

Red and black Trees

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.