Love and hate red-black tree

BST

Abuse you a million times, but also to her first love of red-black tree, whether she was both joy and fear. Do not worry, this article explains, I hope you have ever touched.

Red-black tree is a binary search tree, but the tree to find some more properties than ordinary conditions binary, red or black markings are stored on each node. Because it is a binary search tree, so he has a binary search tree all the features. Red-black tree is a self-balancing binary search tree, not a chain of data into classes degenerate extreme conditions of data inserted (positive or flashback sequence), you can find a more efficient completion in O (log (n)) time , insert, delete operation.

ready

Before reading this article, I recommend that you read the article "interpretation and implementation of a binary search tree" , can help you better understand the red-black tree.

characteristic

  1. Nodes are red or black
  2. Root must be black
  3. Leaf node (appointment is null) constant black
  4. A node to any node on the number of black leaf nodes of each path are equal
  5. It does not allow two consecutive nodes are red, that is the parent node and the child nodes are not red

Seek

Red-black tree search methods and principles of the articles are about the same, there is not re-tell to the node [38,20,50,15,27,43,70,60,90], for example, returns a red-black tree.

Red-black tree

Normal operation

Insert and remove red-black tree is divided into a variety of circumstances, it is relatively complicated. Inserted or deleted after the new tree node, it must meet five characteristics above binary search tree, so the tree to be adjusted by different means. However, normal operation is a binary search tree and the general operation of the same.
For example, ordinary insertion, since each node can only be red or black, so we define non-root newly added default color is red. The new node is defined as the red color of 4 to meet the characteristic (a node to any node on the number of black leaf nodes of each path are equal), otherwise it will be more rules to break a black node.
Now inserted in the tree 10 nodes.

Insertion junction 10

Can be seen from the figure, the parent node is a black node 15, the node 10 is inserted into red, black without increasing the number of nodes, but also other rules not affected, so that, when the parent node of the insertion node is black when directly into the tree, red-black tree does not destroy the original rules.
The case code implements:
a nub

package com.ytao.rbt;

/**
 * Created by YANGTAO on 2019/11/9 0009.
 */
public class Node {

    public static String RED = "red";
    public static String BLACK = "black";

    public Integer value;

    public String color;

    public Node left;

    public Node right;


    public Node(Integer value, String color, Node left, Node right) {
        this.value = value;
        this.color = color;
        this.left = left;
        this.right = right;
    }

    public Node(int value, String color) {
        this.value = value;
        this.color = color;
    }
}

Achieve operation

public void commonInsert(Node node, Integer newVal){
    if (node == null)
        node = new Node(newVal, Node.BLACK);
    
    while (true){
        if (newVal < node.value){
            if (node.left == null){
                // 如果左树为叶子结点并且父结点为黑色,可以直接插入红色新结点
                if (node.color == Node.BLACK){
                    node.left = new Node(newVal, Node.RED);
                    break;
                }
            }
            node = node.left;
        }else if (newVal > node.value){
            if (node.right == null){
                if (node.color == Node.BLACK){
                    node.right = new Node(newVal, Node.RED);
                    break;
                }
                
            }
            node = node.right;
        }
    }
}

See this code, whether the feeling of deja vu, yes, this is the last article of the insert added a color restrictions.
The same is true for deletions, not here in detailing.

Discolor

In order to better analyze the color clarity reasons, the node 50 will be extracted as the tree root, as shown:

50 as the root node of the tree

55 added to the tree the node in the tree shown in FIG obtained:

Adding node 55

Then 55 and 60 are red nodes, does not meet the characteristics of the red-black tree (do not allow two consecutive nodes are red), then we need to adjust, then use to change color.
The parent node 60 turns black, and red-black tree that does not meet the characteristics (either a node on each path of black leaf node number of nodes are equal), because we added black node 60, and more out of a black node.
At this time node 70 is necessarily black, because the color of the original parent node 60 is red. The node 70 turns red, the left subtree meet taking 70 points, but the right sub-tree node 70 turns red by the impact of fewer black node, the node 90 is just red, it can become black, to meet the requirements the right subtree of the node 70.
This kind of special case processing is relatively simple, can be simply processed by discoloration.

After color adjustment

Red-black tree structure to achieve these conditions:

public void changeColor(Node node, int newVal){
    if (node.left == null || node.right == null)
        return;
    // 通过判断待插入结点的父结点和叔叔结点,是否满足我们需要的条件
    if (node.left.color == Node.RED && node.right.color == Node.RED){
        // 确定是更新到左树还是右树中
        Node base = compare(newVal, node.value) > 0 ? node.right : node.left;
        // 和待插入结点的父结点作比较
        if (newVal < base.value && base.left == null){
            base.left = new Node(newVal, Node.RED);
        }else if (newVal > base.value && base.right == null){
            base.right = new Node(newVal, Node.RED);
        }
    }
    node.color = Node.RED;
    // 通过取反获取插入结点的叔叔结点并将颜色变黑色
    Node uncleNode = compare(newVal, node.value) > 0 ? node.left : node.right;
    uncleNode.color = Node.BLACK;
}

public int compare(int o1, int o2){
    if (o1 == o2)
        return 0;
    return o1 > o2 ? 1 : -1;
}

Rotation

When a color can not be solved only by the characteristics we need to meet, we will consider the use of rotating red-black tree.
Insertions and deletions in the rotation, frequently used in the operation, in order to meet our five properties can be generated by a new red-black tree, the rotation is divided into left rotation and right rotation.

Left rotation

L turned counterclockwise rotation, similar to the parent node toward left (right and left direction of the rotation may be distinguished such memory), as shown in FIG transformation:

Left rotation

Right rotation

Right rotation and left rotation the opposite direction, the other are the same, as shown in FIG transformation:

Right rotation

As can be seen from the figure, the parent-child nodes rotated, the relation reversed, the sub-node to child nodes while the parent node.
If the rotation is left, then the parent node will be rotated left child node node; the left child node child nodes will be the right child node of the parent node.
If it is right rotation, then the parent node will be the right child node of rotation nodes; right child nodes child nodes will be the left child node of the parent node.
Sounds more mouthful, remember one rule, small left and right large, with two rotating on the map is easier to understand.
Rotating implemented in code as follows:

/**
 *
 * @param node 两个旋转结点中的父结点
 * @param value 两个旋转结点中子结点的值,因为在整合旋转的时候,node可以遍历查找出来,value作为需要旋转的标记结点
 */
public void rotate(Node node, int value){
    Node nodeChild = compare(value, node.value) > 0 ? node.right : node.left;
    if (nodeChild != null && value == nodeChild.value){
        Node parent = node;
        // 旋转子结点小于旋转父结点,执行的是右旋转,否则为左旋转
        if (value < node.value){
            rightRotate(parent);
        }else if (value > node.value){
            leftRotate(parent);
        }
    }
}

/**
 * 左旋转
 * @param node 旋转的父结点
 */
public void leftRotate(Node node){
    Node rightNode = node.right;
    // 旋转结点的左子结点给父结点的右子结点
    node.right = rightNode.left;
    // 父结点作为子结点的左子结点
    rightNode.left = node;
}

/**
 * 右旋转
 * @param node
 */
public void rightRotate(Node node){
    Node leftNode = node.left;
    // 旋转结点的右子结点给父结点的左子结点
    node.left = leftNode.right;
    // 父结点作为子结点的右子结点
    leftNode.right = node;
}

Case rotating color applications

Above the junction 38 of junction 55 is inserted into red and black. After application of the foregoing explanation of the discoloration to red-black tree structure shown in FIG:

In this case does not satisfy the characteristic red-black trees (two consecutive nodes are not allowed to red), then we need to node 50 and the node 38 for left rotation, to obtain the following diagram:

50 do not meet the red-black tree root characteristics (root must be black), so after the first root becomes black.

The resulting red-black tree now, appeared (the number of black nodes on each path are equal to any of a node to the leaf node) departing from the characteristics, a multi-black tree left than the right node tree, at which time 38.20 , 15, 27 color change.

Here after color adjustment operation is completed the rotation of the above red-black tree that lesson tree.

Since the code length is larger, and not all possible cases are taken into account. I believe understanding the red-black tree implementation is not a big problem for coding.

to sum up

Operation red-black tree is a binary search tree based on common plus red-black tree properties, either insert or delete operation, which is rotated to adjust the color red-black tree tree structure in general, so understanding black tree time, mainly to the rotation, color, using a rotating color characteristics to meet the red-black tree, the essence of which is the red-black tree. Understand its principles and design ideas, an application to solve practical problems is indeed a very good design. Of course, the red-black tree is changing in the actual operation, the complex, to fully grasp or to take the time to study.




Personal blog: https://ytao.top
my public number ytao
My public number

Guess you like

Origin www.cnblogs.com/ytao-blog/p/11848154.html