C + + Learning--build a simple&little rb_tree

Source: Internet
Author: User

Why would we go to such ludicrous lebgths to explain the rb_tree?

"STL Source Analysis" gave us a good explanation: (see page 202)
The so-called tree-shape balance does not have an absolute measurement standard. The general meaning of "balance" is that no one node is too deep (the depth is "the path length of the root node to any node, the so-called depth of the node", which is equal to the length of the path in value). Different equilibrium conditions, creating different efficiency performance, and different implementation complexity. There are a number of special structures such as: avl-tree,rb-tree,aa-tree, can achieve a balanced binary search tree, they are more complex than the general (can not be absolutely balanced) binary search tree, therefore, the average time to insert nodes and delete nodes is also relatively long, But they can avoid extremely difficult (highly unbalanced) worst-case scenarios, and because they always maintain a certain level of balance, the element's access (search) time is generally less, and in general its search time can save about 25%

The rb_tree of a balanced binary search tree. Not only is it a binary search tree, it should also meet the following rules:

Summed up that is "one foot black, black and red do not connect":
We have agreed on four rules:
(1) Each node is either red or black
(2) The root node must be black (that is, one foot is black, one of which refers to a null node)
(3) If the node is red, its child nodes must be black (that is, red is not connected)
(4) Any path of any node to null (the end of the tree), which must contain the same number of black nodes. (ie Black)

Here is the Rb_tree code && Explanation: (You also can actualize it. Believe yourself!)

/ * Header file * /#include <iostream>#include <assert.h> //for assert #include <string.h> //for memset /*memset Usage: * void *memset (void *s, int c, size_t n); * the memset () function fills the first n bytes of the memory AR Ea* pointed to by s with the constant byte c.*/using namespace STD;/ * tree node color Use enumeration type to define how *typedef is used see my other article [typedef usage Summary] (http://blog.csdn.net/derkampf/article/details/51339953) * This is used to define the type of real values that are stored in the node. */typedef intType;typdefenum{red=0, Black}color;typedef structnode{color color; Type key;structNode *left, *right, *parent; }*pnode;the type of the//node is pointer typetypedef struct{Node *root; Node *nil;} Rb_tree;//rb_tree node content, nil as a tool, for subsequent tree nodes of the assignment, the empty functionnode* Buynode () {Node *p =NewNode; ASSERT (P! = NULL);memset(P,0,sizeof(Node));//For new node node initialization, {color = RED, key = 0, left = 0x0, right = 0x0, parent = 0x0}    returnP;}voidInittree (Rb_tree &t)//Create a node and initialize it{T.nil = Buynode ();    T.root = T.nil;    T.nil->color = BLACK; T.nil->key =-1;}/* Left-hand, right-handed, and the red-black-tree Balanced code is then analyzed after insertion */BOOLInsert (Rb_tree &t, Type x)//Insert node{Node *p = T.nil; Node *s = t.root;/ * Start traversing from the root node, find the location that belongs to the new node Q, insert it * /     while(s! = T.nil) {p = s;if(x = = S->key) {return false; }Else if(x < S->key) {s = s->left;//Description x position should be found at this time S's left tree position}Else{s = s->right;//Then the position at which X should be inserted should continue to look in the right tree of S}    }/ * Arrived at this step, the program has found the location of the new node, the next thing to do is: Create a new empty node Q, the value of X to the node (which constitutes the new node we want to insert) * /Node *q = Buynode (); Q->key = x; q->parent = p;//Think about it, Q->parent = S is not written here, because the program executes here when s = T.nil, that is, S is null    / * Follow-up operation * /    if(p = = t.nil)//Here I feel I can not have this condition, because at this time P is present{t.root = q; }Else if(x < P->key)    {p->left = q; }Else{p->right = q;    } q->left = Q->right = T.nil; Q->color = RED;//New Insert node color must be redInsert_fixup (T,Q);//need to be further amended, yes. Meet Rb_tree rules    return true;}intMain () {intAr[] = {5,7,Ten};    Rb_tree RB; Inittree (RB); for(inti =0; i<sizeof(AR)/sizeof(int);    ++i) {Insert (RB, Ar[i]); }return 0;}

The inserted node destroys the Rb_tree rule, causing us to rotate the tree and adjust the color of the nodes. The book gives us four ways of thinking.
"Based on the X's insertion position, which is the color of the peripheral node (the Uncle S node and the GG Great grandfather node), there are four considerations."
--"STL Source code Analysis"
Because it is a simple implementation, we only want to analyze the situation of single rotation. I will continue to update the SGI–STL version of the Red and black tree implementation process, please look forward to!
The following is the left and right rotation, and the code to balance the red and black trees after insertion:
The situation is as follows:

(See the "STL Source Analysis" page 210 for details, here is no longer repeat)

//With the tree above, getting the following code is obviousvoidRotateleft (Rb_tree&T, Node*P) {Node*S=P -Right P -Right=S -Leftif(s -Left!=T.Nil) {s -Left -Parent =P } s -Parent =P -Parent;if(p -Parent =T.Nil) {T.Root=S }Else if(p=P -Parent -left) {p -Parent -Left=S }Else{p -Parent -Right=S } s -Left=P P -Parent =s;}

//The top is right-handed, so you can write a general-purpose right-handed code as long as you take into account the various situations that arise. voidRotateright (Rb_tree&T, Node*P) {Node*S=P -Left P -Left=S -Rightif(s -Right!=T.Nil) {s -Right -Parent =P } s -Parent =P -Parent;if(p -Parent ==T>Nil) {T.Root=S }Else if(p==P -Parent -left) {p -Parent -Left=S }Else{p -Parent -Right=S } s -Right=P P -Parent =s;}

What we need to know is that a piece of code is used to solve a problem, and if you take into account all the possible scenarios, then this code can perfectly solve all the situations that occur in this problem. Just like the above-mentioned left-hand, right-handed code, we use it only to solve the problem of left-handed, or right-handed, when writing code, we have taken into account the situation in this process, then it is not only confined to the simple tree, but all need to be left-handed or right-handed tree.

void Insert_Fixup(RB_TREE &t, Node *z){    }

C + + Learning--build a simple&little rb_tree

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.