Use the java. util. TreeMap source code to understand the red and black trees,

Source: Internet
Author: User

Use the java. util. TreeMap source code to understand the red and black trees,
Preface

This article combines the TreeMap source code of JDK1.6 to explore the mysteries of the Red-black tree. The red/black tree solves the imbalance problem of the Binary Search Tree.

When a new node is inserted (or deleted), certain rules must be followed to keep the tree in balance. This rule is a red-black rule:
1) each node is either red or black
2) the root is always black.
3) if the node is red, its child node must be black (otherwise it may not be true)
4) each path from the same to the leaf node or an empty sub-node must contain the same number of black nodes

Insert a new node

The Insert Process of the Red-black tree is basically the same as that of the common Binary Search Tree: From the point with the insert point, at each node, you can compare the relative size of the node keyword to determine whether to move left or right.

1 public V put (K key, V value) {2 Entry <K, V> t = root; 3 int cmp; 4 Entry <K, V> parent; 5 Comparable <? Super K> k = (Comparable <? Super K>) key; 6 do {7 parent = t; 8 cmp = k. compareTo (t. key); 9 if (cmp <0) {10 t = t. left; 11} else if (cmp> 0) {12 t = t. right; 13} else {14 // note that the return exit method is 15 return t. setValue (value); 16} 17} while (t! = Null); 18 Entry <K, V> e = new Entry <K, V> (key, value, parent); 19 if (cmp <0) {20 parent. left = e; 21} else {22 parent. right = e; 23} 24 fixAfterInsertion (e); 25 size ++; 26 modCount ++; 27 return null; 28}

However, in the red-black species, finding insertion points is more complex because of color conversion and rotation.fixAfterInsertion()The method is to deal with color transformation and rotation. You need to know how to maintain the balance of the tree (use rotations and the color rules to maintain the tree's balance ).

In the following discussion, X, P, and G are used to represent the associated nodes. X indicates a special node. P is the parent of X, and G is the parent of P.

X is a node that has caused a rule violation. (Sometimes X refers to a newly inserted node, and sometimes to the child node when a parent and child have a redred conflict.)

On the way down the tree to find the insertion point, you perform a color flip whenever you find a black node with two red children (a violation of Rule 2). Sometimes the flip causes a red-red conflict (a violation of Rule 3). Call the red child X and the red parent P. The conflict can be fixed with a single rotation or a double rotation, depending on whether X is an outside or inside grandchild of G. Following color flips and rotations, you continue down to the insertion point and insert the new node.

After you’ve inserted the new node X, if P is black, you simply attach the new red node. If P is red, there are two possibilities: X can be an outside or inside grandchild of G. If X is an outside grandchild, you perform one rotation, and if it’s an inside grandchild, you perform two. This restores the tree to a balanced state.

According to the above explanation, the discussion can be divided into three parts:
1) Color flips on the way down)
2) rotation after the inserted node (Rotations after the node is inserted)
3) Rotations on the way down)

Color flips on the way down)

Here’s the rule: Every time the insertion routine encounters a black node that has two red children, it must change the children to black and the parent to red (unless the parent is the root, which always remains black)

The flip leaves unchanged the number of black nodes on the path from the root on down through P to the leaf or null nodes.

Although color conversion does not violate rule 4, it may violate rule 3. If the parent of P is black, there will be no problem when P is changed from black to Red. However, if the parent of P is red, after the color of P changes, there are two red nodes connected. This problem needs to be solved before you continue to insert a new node along the path. You can fix this problem by rotating it. We will see it below.

Rotation after the node is inserted (Rotations after the node is inserted)

Before the new node is inserted, the tree conforms to the red-black rule. After the new node is inserted, the tree is not balanced. At this time, you need to adjust the tree balance through rotation, to re-comply with the red-black rules.

Possibility 1: P is black, so you don't need to do anything. Insert.

Possibility 2: P is red, and X is an external child node of G. You need to rotate it at a time and change the color.
Take inserting 50, 25, 6 as an example. Note that node 6 is an external child node, and its parent node is red.

In this example, X is an outer child node and a left child node. X is a outer child node and the right child node. X is symmetric with this. Create a tree with 50, 25, 75, 87, and 93, and draw a picture again, which is omitted here.

Possibility 3: P is red, X is an inner child node of G, it needs to be rotated twice and some color changes.
Take inserting 50, 25, and 18 as an example. Note that node 18 is an inner child node, and its parent node is red.

Rotations on the way down)

Before inserting a new node, the tree actually violates the red-black rule, so you need to adjust it before inserting the new node. Therefore, the topic of this discussion is "when we are going down the road to prepare to insert a new node, we will first adjust the above to make it a standard red-black tree and then insert a new node ".

Outer Child Node

Taking the insertion of, as an example, the node that violates the rules in this example is an outer child node.

Inner child node

Taking inserting 50, 25, and 43 as an example, the node that violates the rules in this example is an inner child node.

Efficiency of the Red-black tree

Like the common Binary Search Tree, the time complexity of searching, inserting, and deleting the red-black tree is O (log2N ).

The search time of the Red-black tree is almost the same as that of the common Binary Search Tree. Because the red-black feature is not used in the search process. The additional overhead is that the storage space of each node is slightly increased to store the red and black colors (a boolean variable ).

final Entry<K, V> getEntry(Object key) {    Comparable <? super K > k = (Comparable <? super K > ) key;    Entry<K, V> p = root;    while (p != null) {        int cmp = k.compareTo(p.key);        if (cmp < 0) {            p = p.left;        } else if (cmp > 0) {            p = p.right;        } else  {            return p;        }    }    return null;}

A constant factor must be added to the insertion and deletion time, because color conversion and rotation must be performed on the downstream path and the insertion point. On average, one insert operation requires about one rotation.

In most applications, the number of searches is more than the number of inserts and deletions, so the red-black tree of the application replaces the ordinary Binary Search Tree, which does not increase the time overhead.

References

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.