Insert and remove red-black tree

To know what is the red-black tree, we must first understand what is a binary search tree.

What is a binary search tree?

Binary search tree features:
1) a left subtree of the value of all the nodes are less than or equal to its root
2) the value of the right subtree of all nodes are equal to or greater than the value of the root node
3) approximately subtree certainly is binary sort tree

Here is a standard binary search tree:

we have to find a binary operation when adding or removing a node in the tree, the tree will tilt the situation, such as the following case:

In order to solve this problem, resulting in a red-black tree .
What is the red-black tree?

Red-black tree features:
1) a red or black node
2) is black root node
3), each leaf node is empty black
4) two child nodes of each node are black red
5) from any node to all of its path for each leaf node contains the same black

As long as these five characteristics, is a red-black tree, red-black tree balancing operations, but also for the five characteristics to do. Here are some red-black tree is how to insert and delete operations.

Red-black tree insert:

We assume that the current state of the red-black tree shown below

we insert a node 25 to which, after insertion as follows:

In order to meet the five properties, the initial state of node 25 must be red node, we have found that node 26 is its parent red node, breaking the 4 characteristics: two children of each red node are black, red-black tree need to make adjustments at this time

Adjustment:

1) color

由于26不满足特性4,所以将26变为黑节点

这样又违背了特性5,所以把28变为红节点

此时,如果继续将节点24变为黑色,那么节点16将无法变换,所以根节点需要进行左旋转(24作为根节点,它的父节点作为它的左子树,它的左子树作为父节点的右子树)

此时不满足特性2,根节点必须为黑色,所以将根节点变为黑色

此时以节点16为根的子树不满足特性5,所以将节点16进行右旋转

根据规则,将节点16变为红节点

调整结束

由此我们就会发现,红黑树的五个特性互相制约,确保了红黑树中除叶子节点外,相同颜色的两个节点不会相连,进而保证了不会出现某条路径比其他路径长出两倍的情况

在对红黑树进行平衡的过程中,要尽量进行变色操作,一旦发现变色解决不了问题了,才会对其进行旋转

红黑树的删除:

想要对红黑树进行删除操作,首先要把它当做一颗二叉查找树,对二叉查找树进行节点的删除,然后再对其做平衡调整

二叉查找树节点的删除主要有以下几种情况:
1)待删除的节点无左右孩子
此时只需要将该节点直接删除就好
2)带删除的节点只有左孩子或者右孩子
此时需要将该节点删除,并让它的父节点指向他的左孩子或是右孩子
3)待删除的节点既有左孩子又有右孩子
首先需要找出它的右子树的最左孩子,换句话来说就是右子树中最小的节点,然后将该节点与待删除的节点进行互换,最后将该节点删除,因为是交换的节点是它右子树的最左孩子,所以该节点只会有两种情况
1)该节点无左右孩子,此时对应情况1
2)该节点有右孩子,此时对应情况2
根据具体的情况,进行对应的操作就好了
这样,我们就完成了节点的删除,下面需要对红黑树进行平衡了

我们看下面这张图:

假如我们要删除节点26,我们可以看到满足情况1,该节点无左右孩子,所以我们可以直接把节点26删除,删除之后就是下面这个样子:

此时,我们发现从根节点开始遍历,遍历到左节点所经过的黑色节点数与遍历到有右节点所经过的黑色节点数不同,此时需要对其进行平衡。若要使其满足
特性五,我们发现无法通过简单的变色操作进行平衡,所以需要对其进行右旋,旋转之后的红黑数就是下面这个样子

然后为了满足条件1,我们把根节点变为黑色

然后我们发现遍历右子树的叶子节点经过的黑色节点数要多于左子树,所以将节点24变为红色,再把节点28变为黑色:

这样就完成了红黑树的删除操作啦。

Guess you like

Origin www.cnblogs.com/JoshWill/p/12003351.html