1

我正在阅读有关红黑树的信息,并且我知道节点可以是红色或黑色。规则说:

1) 每个节点都有一种颜色——红色或黑色。

2)树的根总是黑色的。

3)没有两个相邻的红色节点(一个红色节点不能有一个红色的父节点或红色的孩子)

4) 从一个节点(包括根节点)到它的任何后代 NULL 节点的每条路径都有相同数量的黑色节点。

没有说明哪些节点应该编码为红色?我知道树可以有所有黑色节点,但我不明白的是我们什么时候应该将节点标记为红色?

我还想了解这种颜色编码背后的原因。我知道 RB 树基本上是一棵自平衡树,但我想了解这种二进制颜色编码对此有何帮助?

4

1 回答 1

0

通常的方法是在插入时将所有节点涂成红色,然后执行修复,插入红色节点可能根本不会产生任何违规,但插入黑色节点总是会。

基本插入算法:

insert value as for any BST, coloring the node red if a new node is created, done if the value is already present
LOOP:
if node is tree anchor then set node's color to black and done
if node's parent's color is black then done
if node's uncle's color is red then flip colors of node's parent, node's uncle and node's grandparent, set node to node's grandparent and go to LOOP
if node's parent and node have different orientations then rotate node's parent so that node's parent becomes child to node
otherwise set node to node's parent
flip colors of node and node's parent
rotate at node's parent so that node's parent becomes child to node
done
于 2020-06-13T21:20:46.333 回答