# RedBlackTree_II

The Last Section

## Basic operation of red black trees

### Insert

Insert a node into the red-black tree, which steps need to be performed?

1. think of the red-black tree as a binary search tree and insert the node.
2. Set this node to red.
3. Modify the tree by rotating and recoloring it to make it a red-black tree again.

#### Step Description

##### Step 1

The red-black tree is a binary search tree, which is still a binary search tree after the node is inserted. This means that the key of the tree is still ordered. In addition, whether it is left-rotation or right-rotation, the tree is a binary search tree before rotation, and after rotation it must be a binary search tree.

##### Step 2

Why should set the node’s color to red?

Because it is not violate 5 features. violate more less feature mean less things we need to deal with.

##### Step 3

So how many features it violate?

1. As for feature 1, obviously not violate.
2. As for feature 2, insert operation does not change the root node, so the color of root node is still black.
3. As for feature 3, leaf node is null node, inserting non-null node does not affect feature.
4. As for feature 4, Is possible to violate.

#### Case Description

##### Case 1
###### Description

The current node’s parent node is red, and the current node’s grandparent node’s other child node (uncle node) is also red

Grandfather node must exist at this time, otherwise it is not black red tree before inserting. At this point is divided into the parent node is the grandfather’s left child or right child, according to symmetry, we just untie a direction on it. Here only consider the parent node left grandfather’s situation, as shown below.

###### Method

Strategy is as follows:

1. Sets the parent node to black.
2. Sets the node of the uncle to black.
3. set grandfather node to red.
4. The grandfather node is set as the current node (red node).

As shown in the following pseudo code:

Then, insert repair case 1 translates into insert repair case 2.

##### Case 2
###### Description

The current node’s parent node is red, the uncle node is black, and the current node is the right child of its parent node

###### Method

Strategy is as follows:

1. Set the parent as the new current node.
2. Do left rotation on current node.

As shown in the following pseudo code:

Insertion Repair Case 2 translates into insert repair case 3.

##### Case 3
###### Description

The current node’s parent node is red, the uncle node is black, and the current node is the left child of its parent node

###### Method

Strategy is as follows:

1. Sets the parent node to black.
2. set grandfather node to red.
3. Do right rotation on grandfather node.

As shown in the following pseudo code:

The Next Section

Share