The clearest red and black tree in history (on)

Source: Internet
Author: User
Tags comparable

Http://www.cnblogs.com/CarpenterLee/p/5503882.html

This article takes Java TreeMap as an example, from the source code level, combined with detailed illustrations, silking the insertion, deletion and the resulting adjustment process of the red-black tree (red-black trees).

General Introduction

Java TreeMap implements the SortedMap interface, which means that the key elements in the Map are sorted in order of size, key The size can be judged by its own natural order (natural ordering), or by constructing an incoming comparator (Comparator).

The TreeMap Bottom is realized by the red and black trees (red-black tree) , which means,,, containsKey() get() put() remove() All log(n) of the time complexity. Its specific algorithm implementation refers to the introduction of the algorithm.

For performance reasons, theTreeMap is non-synchronous (not synchronized) and needs to be manually synchronized by the programmer if it needs to be used in a multithreaded environment, or as follows TreeMap Packaged into (wrapped) synchronized:

SortedMap m = Collections.synchronizedSortedMap(new TreeMap(...));

The red-black tree is an approximately balanced two-fork lookup tree that ensures that the height difference of the left and right subtrees of any one node does not exceed the lower of the two. Specifically, the red-black tree is a two-fork search tree that meets the following conditions:

    1. Each node is either red or black.
    2. The root node must be black
    3. The red node cannot be contiguous (that is, the child and father of the red node cannot be red).
    4. For each node, any path from that point to (the end null of the tree) contains the same number of black nodes.

When the structure of the tree changes (insert or delete operations), often break the above conditions 3 or condition 4, need to adjust so that the search tree to meet the conditions of the red and black trees.

Pre-knowledge

In the previous article, when the structure of the search tree changes, the conditions of the red-black tree may be destroyed, and the search tree needs to be adjusted to meet the conditions of the red-black tree. Adjustment can be divided into two categories: one is color adjustment, that is, change the color of a node, the other is the structure adjustment, set to change the structure of the search tree relationship. The structure adjustment process consists of two basic operations: left- Hand (Rotate left) and right-handed (rotateright).

L

The left-hand process is to x rotate the right subtree around counterclockwise x , making x the right subtree the x father, while modifying the reference of the associated node. After rotation, the properties of the binary lookup tree are still satisfied.

TreeMap The left-hand code is as follows:

Rotate LeftPrivate void Rotateleft(Entry<k,v> p) {if (P! =NULL) {entry<k,v> r = P.Right P.right = R.left; if (R.left! = null) r.left.parent = P.parent; if (P.parent = = null) root = R; else if (p. parent. left = = p) p.parent.else p.parent.left = p; p.parent = r;}}          
Right-handed

The right-hand process is to x rotate the left subtree x around clockwise so that x the left subtree becomes x the father, while modifying the reference of the associated node. After rotation, the properties of the binary lookup tree are still satisfied.

The right-hand code in TreeMap is as follows:

Rotate RightPrivate void Rotateright(Entry<k,v> p) {if (P! =NULL) {entry<k,v> L = p.Left P.left = L.Right ; if (L. right ! = null) L . Right. parent = p; L.parent = p.parent; if (p.parent = = null) root = l; Else if (p.parent.  right = = p) p.parent.  right = L; Else P.parent.  left = l; L. Right= P; p.parent = l;}}             
Method anatomy Get ()

get(Object key)Method is returned according to the specified key value value , and the method call getEntry(Object key) gets the corresponding entry , and then returns entry.value . Therefore getEntry() is the core of the algorithm. The algorithm is based on key the natural order (or comparator order) to find the two-fork search tree until it finds k.compareTo(p.key) == 0 a satisfying one entry .

The specific code is as follows:

Getentry () methodFinalEntry<k,v>Getentry(Object key) { ......if (key = =NullThe key value is not allowed to be nullThrowNew NullPointerException (); comparable<?Super k> K = (comparable<?Super k>) key;Use the natural order of the elements entry<k,v> p = root;while (P! = null) {int cmp = K.compareto (P.key); if (CMP < 0)  //left to find p = P.left; else if (cmp > 0) //right-looking p = P.right; else return p;} return null;}     
Put ()

put(K key, V value)The method is to add the specified key , pairs to the value map inside. The method first makes a map lookup to see if the tuple is included, and if it is included, it is returned directly, the lookup process is similar to a getEntry() method, and if it is not found, a new one is inserted in the red-black tree, and if the constraint of the entry red-black tree is broken after insertion, it needs to be adjusted (rotated, Change the color of some nodes).

PublicVPut(K key, V value) { ......int CMP; Entry<k,v> parent;if (key = =NullThrowNew NullPointerException (); comparable<?Super k> K = (comparable<?Super k>) key;Use the natural order of the elementsdo {parent = t; cmp = K.CompareTo (T.Key);if (CMP <0) T = T.LeftLook left.Elseif (CMP >0) T = T.RightLook right.else return T. setvalue (value);} while (t! = null); entry<k,v> e = new entry<> (key, value, parent); //Create and insert a new entry if (CMP < 0) parent. left = e; else parent.fixafterinsertion (e); //adjust size++; return null;}    

The insertion of the above code is not difficult to understand: first find the appropriate location on the red and black tree, then create a new entry and insert (of course, the newly inserted node must be the leaf of the tree). The difficulty is the adjustment function fixAfterInsertion() , which has been said before, the adjustment often requires 1. Change the color of some nodes, 2. Rotate some nodes.

The fixAfterInsertion() specific code for the adjustment function is as follows, which uses the rotateLeft() and functions mentioned above rotateRight() . Through the code we can see that the situation 2 actually falls within the situation 3. Situation 4~ situation 6 in front three cases are symmetrical, so the diagram does not draw the following three cases, the reader can refer to the code to understand their own.

Red and black tree adjustment function fixafterinsertion ()Private void Fixafterinsertion(Entry<k,v> x) {x.color = RED;while (x! =Null && x! = root && X.Parent.color = = RED) {if (Parentof (x) = =Leftof (Parentof (Parentof (x)))) {Entry<k,v> y =Rightof (Parentof (Parentof (x)));if (Colorof (y) = = RED) {SetColor (Parentof (x), BLACK);Scenario 1SetColor (y, BLACK);Scenario 1SetColor (Parentof (Parentof (x)), RED);Case 1 x =Parentof (Parentof (x));Scenario 1}else {if (x = =Rightof (Parentof (x))) {x =Parentof (x);Scenario 2Rotateleft (x);Scenario 2}SetColor (Parentof (x), BLACK);Scenario 3SetColor (Parentof (Parentof (x)), RED);Scenario 3Rotateright (Parentof (Parentof (x)));Scenario 3}}else {entry<k,v> y =Leftof (Parentof (Parentof (x)));if (Colorof (y) = = RED) {SetColor (Parentof (x), BLACK);Scenario 4SetColor (y, BLACK);Scenario 4SetColor (Parentof (Parentof (x)), RED);Case 4 x =Parentof (Parentof (x));//case 4} else {if (x = = leftof (parentof (x))) {x = parentof (x); //situation 5 rotateright (x); //situation 5} setcolor (parentof (x), BLACK ); //situation 6 setcolor (parentof ( parentof (x)), RED); //situation 6 rotateleft (parentof (parentof (x)); //condition 6}} Root. color = BLACK;}             
Remove ()

remove(Object key)The function is to delete the value corresponding to key entry , the method first find the value corresponding by the method mentioned above getEntry(Object key) key entry , and then call deleteEntry(Entry<K,V> entry) Delete corresponding entry . Because the delete operation will change the structure of the red and black tree, it is possible to destroy the red and black tree constraints, so it is possible to adjust.

The remove() specific explanation will be put in the next blog post, please look forward to!

The clearest red and black tree in history (on)

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.