Illustration set 7: detailed explanation of the concept of the red/black tree, the insertion and rotation operations of the red/black tree, and the interpretation of the red/black tree
Original article address: http://www.cnblogs.com/xrq730/p/6867924.html. please refer to it for help. Thank you!
First knowledge of TreeMap
Previous articles have explained two types of maps, HashMap and LinkedHashMap, which ensure the addition, deletion, modification, and query of O (1) time complexity. From the storage point of view, these two data structures are excellent. In addition, LinkedHashMap ensures that the traversal order of the Map can be consistent with the put order, and solves the unordered problem of the HashMap itself.
Nevertheless, HashMap and LinkedHashMap have their own limitations-theyThey do not have statistical performance, or their time complexity is not very good to be more accurate. All statistics must traverse all entries, so the time complexity is O (N). For example, Map keys include 1, 2, 3, 4, 5, 6, and 7. Now I want to count:
Similar to these operations, HashMap and LinkedHashMap do relatively poorly. In this case, we can use TreeMap. The keys of TreeMap are sorted in the natural order or by the Comparator interface provided when the treing is created.TreeMap provides log (N) time overhead for adding, deleting, modifying, and querying operations.From the storage point of view, this is more complex than the O (1) Time of HashMap and LinkedHashMap. However, in terms of statistical performance, TreeMap can also ensure the time overhead of log (N, this is much more complex than the O (N) Time of HashMap and LinkedHashMap.
Therefore, if you only need the storage function, using HashMap and LinkedHashMap is a better choice. If you need to ensure statistical performance or sort keys according to certain rules, therefore, using TreeMap is a better choice.
Some basic concepts of the red/black tree
Before talking about TreeMap, let's talk about some basic concepts of the red and black trees, so that we can better understand the source code of the TreeMap.
The binary search tree is prone to imbalance during generation.The worst case is one-sided (that is, only the left/right subtree), which greatly reduces the tree search efficiency. (For details about the tree and Binary Search Tree, refer to the tree structure I wrote earlier)
The red-black tree is a tree generated to maintain the balance of the Binary Search Tree. According to Wikipedia, the red-black tree has five features, but I don't think it is easy to understand, to sum up, there are roughly three features of the red/black tree (in other words,After a node is inserted or deleted, the entire Red/black tree must satisfy the following three properties. If not, it must be rotated.):
The above properties constrain the key of the red and black trees:The maximum possible paths from the root to the leaves are no more than twice the maximum possible paths.. The reason for this conclusion is:
At this time, (2) is exactly twice the length of (1. The result is that the tree is roughly balanced, because operations such as inserting, deleting, and searching for a value must be in the worst case in proportion to the height of the tree, the theoretical ceiling of this height allows the red and black trees to be efficient in the worst case. Unlike the ordinary binary search treeThe red/black tree can be searched, inserted, and deleted with O (log2 n) time complexity..
The following is an example of a red/black tree:
We can see that the black nodes from the root node to all the null leaf nodes (that is, the LEAF node) are two.
In addition, we can draw a conclusion from this figure:The red and black trees are not the height of the Balance Tree.. The so-called balanced tree refers to an empty tree or its left and right subtree. The absolute value of the height difference cannot exceed 1, but we can see:
- The leftmost path is 0026 --> 0017 --> 0012 --> 0010 --> 0003 --> null leaf. Its height is 5.
- Path of the last edge: 0026 --> 0041 --> 0047 --> null leaf. Its height is 3.
The height difference between left and right Subtrees is 2, so the red and black trees are not highly balanced. They give up the highly balanced feature and only pursue partial balance, this feature reduces the requirements for tree rotation during insertion and deletion, thus improving the overall performance of the tree. While other balancing trees, such as AVL trees, have O (logn) search performance, they may be rotated multiple times during insertion or deletion to maintain their balance, produce relatively large consumption.
Answers with four focus on LinkedHashMap
| Close note |
Conclusion |
| Whether to allow null key-value pairs in TreeMap |
Key cannot be blank, Value can be blank |
| Whether repeated data is allowed in TreeMap |
Duplicate keys are overwritten, and repeated values are allowed. |
| Whether TreeMap is ordered |
Sort by Key in the natural order or by the sort algorithm specified by the Comparator Interface |
| Whether the TreeMap thread is secure |
Non-thread security |
TreeMap Basic Data Structure
TreeMap is based onRed/black treeImplementation: since it is a red-black tree, in addition to Key --> Value ing, each node will inevitably store some content unique to the red-black tree node. They are:
The node Java code of TreeMap is defined:
1 static final class Entry<K,V> implements Map.Entry<K,V> {2 K key;3 V value;4 Entry<K,V> left = null;5 Entry<K,V> right = null;6 Entry<K,V> parent;7 boolean color = BLACK;8 ...9 }
Because only red and black are available, the color can be represented by boolean, black is true, and red is false.
Summary of the process for adding data to TreeMap
First, let's take a look at how to add data to TreeMap. The test code is:
1 public class MapTest { 2 3 @Test 4 public void testTreeMap() { 5 TreeMap<Integer, String> treeMap = new TreeMap<Integer, String>(); 6 treeMap.put(10, "10"); 7 treeMap.put(85, "85"); 8 treeMap.put(15, "15"); 9 treeMap.put(70, "70");10 treeMap.put(20, "20");11 treeMap.put(60, "60");12 treeMap.put(30, "30");13 treeMap.put(50, "50");14 15 for (Map.Entry<Integer, String> entry : treeMap.entrySet()) {16 System.out.println(entry.getKey() + ":" + entry.getValue());17 }18 }19 20 }
The following content of this article will show what the data structure looks like after each piece of data is inserted. First, let's take a look at the code implementation of the put Method of treeMap:
1 public V put(K key, V value) { 2 Entry<K,V> t = root; 3 if (t == null) { 4 compare(key, key); // type (and possibly null) check 5 6 root = new Entry<>(key, value, null); 7 size = 1; 8 modCount++; 9 return null;10 }11 int cmp;12 Entry<K,V> parent;13 // split comparator and comparable paths14 Comparator<? super K> cpr = comparator;15 if (cpr != null) {16 do {17 parent = t;18 cmp = cpr.compare(key, t.key);19 if (cmp < 0)20 t = t.left;21 else if (cmp > 0)22 t = t.right;23 else24 return t.setValue(value);25 } while (t != null);26 }27 else {28 if (key == null)29 throw new NullPointerException();30 Comparable<? super K> k = (Comparable<? super K>) key;31 do {32 parent = t;33 cmp = k.compareTo(t.key);34 if (cmp < 0)35 t = t.left;36 else if (cmp > 0)37 t = t.right;38 else39 return t.setValue(value);40 } while (t != null);41 }42 Entry<K,V> e = new Entry<>(key, value, parent);43 if (cmp < 0)44 parent.left = e;45 else46 parent.right = e;47 fixAfterInsertion(e);48 size++;49 modCount++;50 return null;51 }
From this code, we will first summarize several steps for adding data to TreeMap:
1st ~ There is no problem in step 1. The core of the red/black tree should be the restoration after data is inserted in step 2. The corresponding Java code is the fixAfterInsertion method in TreeMap, next, let's take a look at what operations TreeMap has done after each put data, so as to clarify the implementation principle of TreeMap.
Put (10, "10 ")
First, put (10, "10"). Because no node exists in TreeMap, 10 is the root node and the root node is the black node. put (10, "10 ") the subsequent data structure is:
Put (85, "85 ")
Next is put (85, "85"). This step is not difficult. 85 is bigger than 10, so it is on the right node of 10, but because 85 is not the root node, therefore, the fixAfterInsertion method will be executed for data correction. Let's take a look at the code implementation of the fixAfterInsertion method:
1 private void fixAfterInsertion(Entry<K,V> x) { 2 x.color = RED; 3 4 while (x != null && x != root && x.parent.color == RED) { 5 if (parentOf(x) == leftOf(parentOf(parentOf(x)))) { 6 Entry<K,V> y = rightOf(parentOf(parentOf(x))); 7 if (colorOf(y) == RED) { 8 setColor(parentOf(x), BLACK); 9 setColor(y, BLACK);10 setColor(parentOf(parentOf(x)), RED);11 x = parentOf(parentOf(x));12 } else {13 if (x == rightOf(parentOf(x))) {14 x = parentOf(x);15 rotateLeft(x);16 }17 setColor(parentOf(x), BLACK);18 setColor(parentOf(parentOf(x)), RED);19 rotateRight(parentOf(parentOf(x)));20 }21 } else {22 Entry<K,V> y = leftOf(parentOf(parentOf(x)));23 if (colorOf(y) == RED) {24 setColor(parentOf(x), BLACK);25 setColor(y, BLACK);26 setColor(parentOf(parentOf(x)), RED);27 x = parentOf(parentOf(x));28 } else {29 if (x == leftOf(parentOf(x))) {30 x = parentOf(x);31 rotateRight(x);32 }33 setColor(parentOf(x), BLACK);34 setColor(parentOf(parentOf(x)), RED);35 rotateLeft(parentOf(parentOf(x)));36 }37 }38 }39 root.color = BLACK;40 }
Let's look at the 2nd lines of code, itColor the default inserted nodeRed, Which is easy to understand:
According to the nature of the red and black trees (3), the number of black nodes passing through from the root node to all leaf nodes on the leaves is the same. Therefore, if the inserted nodes are colored in black, it is inevitable that the number of black nodes in a path is greater than the number of black nodes in other paths. Therefore, the inserted nodes must be red by default, to maintain the property of the red/black tree (3)
Of course, after the inserted nodes are colored as red nodes, the possible cause is the violation of nature (2), that is, two consecutive red nodes appear. This requires the rotation operation to change the tree structure, solve this problem.
Next, let's take a look at the judgment of Row 3. The first two conditions are met, but because the parent node of node 85 is the root node and the root node is the black node, this condition is not met, if the while LOOP does not go in, execute 30 lines of code directly to color the root node as black (because the root node may be red during rotation, the root node of the Red-black tree must be black, so the root node should be colored again regardless of whether the root node is black ).
After put (85, "85"), the structure of the entire tree becomes:
FixAfterInsertion method Process
Before viewing put (15, "15"), you must first pass the fixAfterInsertion method. 5th rows ~ 21st lines of code and 21st lines ~ The code for the second line is the same. One is to operate the left subtree and the other is to operate the right subtree. Therefore, the first half is the same:
1 while (x != null && x != root && x.parent.color == RED) { 2 if (parentOf(x) == leftOf(parentOf(parentOf(x)))) { 3 Entry<K,V> y = rightOf(parentOf(parentOf(x))); 4 if (colorOf(y) == RED) { 5 setColor(parentOf(x), BLACK); 6 setColor(y, BLACK); 7 setColor(parentOf(parentOf(x)), RED); 8 x = parentOf(parentOf(x)); 9 } else {10 if (x == rightOf(parentOf(x))) {11 x = parentOf(x);12 rotateLeft(x);13 }14 setColor(parentOf(x), BLACK);15 setColor(parentOf(parentOf(x)), RED);16 rotateRight(parentOf(parentOf(x)));17 }18 }19 ....20 }
Note the judgment in line 1. The language description is as follows:Determine whether the parent node of the current node and the left child node of the parent node of the current node are the same node. Translation:Whether the current node is inserted on the left subnodeI will not explain what I don't understand. I can think about it myself. I will use a flowchart to describe the entire code:
Here is a concept of inserting the inner of the Left subtree and the outer of the Left subtree. I will use the figure to represent it:
On the left side is insert outside the left subtree, and on the right side is insert inside the left subtree. You can see from the preceding flowchart that the processing of these two insertion methods is different, the difference is that the latter isInsert multiple left-hand operations on the inside of the Left subtree.
As you can see,The insert operation of the red/black tree only needs to be rotated twice at most.As for the rotation of the red and black trees, we will introduce the code later.
Put (15, "15 ")
After reading the fixAfterInsertion method flow, add data. This time, put (15, "15") is added, which is larger than 10 and smaller than 85, therefore, 15 should eventually be the left subnode of 85, and the red node is inserted by default. Therefore, the structure after inserting 15 as the red node to the left subnode of 85 should be:
However, it is clear that the property of the red and black trees is violated here (2), that is, two red nodes appear consecutively, so the rotation must be performed at this time. Let's look back at the previous fixAfterInsertion process. The previous example shows the left subtree insertion process. The right subtree is the same. We can see that this is the inner of the right subtree, and we need to perform two rotation operations:
Rotation is the most difficult and core operation in the red and black trees. The right-hand and left-hand operations are symmetric operations. In my personal understanding, the right-hand operation is used as an example to perform the right-hand operation on a node x, the essence is:
- Decrease the height of the Left subtree and increase the height of the right subtree.
- Change x to the right subnode of the current position
The same is true for the left-hand side. Remember these two sentences during rotation, which will help us to clearly understand how to rotate in different scenarios.
Let's take a look at (1), that is, "perform a right-hand operation on the parent node of the newly inserted node". The source code is the rotateRight method:
1 private void rotateRight(Entry<K,V> p) { 2 if (p != null) { 3 Entry<K,V> l = p.left; 4 p.left = l.right; 5 if (l.right != null) l.right.parent = p; 6 l.parent = p.parent; 7 if (p.parent == null) 8 root = l; 9 else if (p.parent.right == p)10 p.parent.right = l;11 else p.parent.left = l;12 l.right = p;13 p.parent = l;14 }15 }
The right-hand flow chart shows the process:
Use an example to show the changes of the right-hand nodes,Rotating will not change the node colorThe red and black nodes are not distinguished here. a is the right-handed node:
The left-hand and right-hand operations are symmetric. You can try to turn the left-hand operations on the B node in the right graph into the left graph. Here, I would like to say,To rotate a node, you must specify the node to be rotated.I have read many articles on the Internet that tell you how to rotate the left and right sides. I don't think it makes any sense to tell you how to rotate it from a specific node.
A possible problem here is that B has two subnodes, d and e, respectively, why do I need to get right subnode e to the left subnode OF a instead of the Left subnode d of B in the right-hand mode?
A simple explanation is:If the left sub-node d of B is obtained to the left sub-node of a, B points to a right after B, and B's original right sub-node e becomes a free node, out of the entire data structure.
Back to the actual example, there is another coloring operation after right-handed the node 85 (2), which respectively colors the parent node of x as black and the grandfather node of x as red, the tree structure should be:
Perform a left-hand operation on node 10 (3). the structure after the left-hand operation is as follows:
In the end, the root node is colored black regardless of whether the root node is black. The data structure after 15 is changed to meet the three features of the red/black tree.
Put (70, "70 ")
Put (70, "70") is very simple. 70 is the left child node of 85, because 70's parent node and Uncle node are both red nodes, therefore, you can directly color 70's parent node 85 and 70's uncle node 10 to black, and 70 to red, which meets the characteristics of the red and black trees, the structure after 70 is inserted:
Put (20, "20 ")
Put (20, "20"), the inserted position should be the left child node of 70, the red is inserted by default, after the inserted structure is:
Obviously, there are two consecutive red nodes. The insertion position of 20 is a scenario where the left subtree is inserted outside. Therefore, you only need to color the node and perform a right-hand operation on node 85, after coloring + right-handed, the data structure becomes:
Put (60, "60 ")
In the put (60, "60") operation, node 60 is inserted at the right child node of node 20. Because the parent node and the uncle node of node 60 are both red nodes, therefore, you only need to color the parent node and the uncle node of node 60 in black and the group of father nodes of node 60 in red.
The structure after put (60, "60") is:
Put (30, "30 ")
Put (30, "30"), node 30 should be the left subnode of node 60, so after inserting node 30, it should be like this:
Obviously, this is against the red-black tree nature (2), that is, two red nodes appear consecutively, so rotation is required here.
The put (30, "30") operation is similar to the put (15, "15") operation. It is also the scenario of inserting the inside of the right subtree. You need to rotate the operation twice:
After right-hand + coloring + left-hand, put (30, "30") results should be:
Put (50, "50 ")
The next operation is put (50, "50"), and node 50 is the left subnode of node 60. Because node 50's father's day and Uncle node are both red nodes, therefore, you only need to color the Father's Day and Uncle nodes of node 50 in black and the grandfather nodes of node 50 in Red:
The parent and Uncle nodes of node 50 are both red nodes (Be careful not to be confused!It is the structure after re-coloring, not the structure before re-coloring., The structure is above), so insert node 50 only needs to be colored, this operation itself is no problem, but the key to the problem is, after coloring, consecutive red nodes are displayed, namely, node 30 and node 70. This is why the fixAfterInsertion method is a while loop:
1 private void fixAfterInsertion(Entry<K,V> x) {2 x.color = RED;3 4 while (x != null && x != root && x.parent.color == RED) {5 ...6 }7 }
Because this coloring method colors the grandfather nodes of the inserted nodes in red, the current node must be directed to the grandfather node of the inserted node after coloring, to determine whether a red node is consecutive between the grandfather node and the parent node, rotate and rebalance the red and black trees.
The next question is how to rotate. Are you familiar with Connecting Node 15 to node 70 to node 30? This is the scenario where the inner side of the right subtree is inserted twice. First, perform the right-hand operation on node 70, and the result after the right-hand operation is:
Next, the parent node of node 70 is colored in black, and the grandfather node of node 70 is colored in red (this step does not understand or forget why, let's take a look at the previous explanation of the fixAfterInsertion method). The structure after the coloring is:
The last step is to perform a left-handed operation on node 15 of the parent node 70. The structure after the left-handed operation is as follows:
Restore the properties of the red and black trees:
Postscript
By constantly inserting data into the right subtree of the Red-black tree, This article demonstrates the various situations that may occur when inserting the right subtree and how to handle these situations. The same applies to inserting data on the left.
The red and black trees are still a little difficult. Therefore, I personally suggest that you draw more pictures when learning the red and black trees (like I drew 3 A4 sheets of paper myself, in this way, we can better understand the principle of the red and black trees, especially the principle of rotation.
The insert and Rotate operations of TreeMap have been completed. Later, we will focus on the deletion operations of TreeMap and how to implement some statistical operations (such as finding all nodes with a node larger than 50.