我一直在经历Robert Sedgewick在Algorithms中描述的红黑树。这是插入红黑树的代码。
public void put(Key key, Value val) {
root = put(root, key, val);
root.color = BLACK;
assert check();
}
// insert the key-value pair in the subtree rooted at h
private Node put(Node h, Key key, Value val) {
if (h == null) return new Node(key, val, RED, 1);
int cmp = key.compareTo(h.key);
if (cmp < 0) h.left = put(h.left, key, val);
else if (cmp > 0) h.right = put(h.right, key, val);
else h.val = val;
// fix-up any right-leaning links
if (isRed(h.right) && !isRed(h.left)) h = rotateLeft(h);
if (isRed(h.left) && isRed(h.left.left)) h = rotateRight(h);
if (isRed(h.left) && isRed(h.right)) flipColors(h);
h.N = size(h.left) + size(h.right) + 1;
return h;
}
这是一张可视化红黑修正的图像。
考虑这种情况,当要插入的项目位于顶部3节点的中间时。我们必须执行三个if语句中给出的三个操作,即h=rotateLeft(h)
,h=rotateRight(h)
和flipcolors(h)
。问题在于我们分配h = rotateLeft(h)
时。返回的节点是指向具有两个连续左红色链接的三个节点中的中间节点的指针。但该算法假设返回的节点是3节点中的顶级节点,具有2个连续的左红色链接。所以,当我们再次rotateRight(h)
时,我们最终会得到相同的位置。可能是我还没理解算法。
以下是rotateLeft(h)
private Node rotateLeft(Node h) {
assert (h != null) && isRed(h.right);
Node x = h.right;
h.right = x.left;
x.left = h;
x.color = x.left.color;
x.left.color = RED;
x.N = h.N;
h.N = size(h.left) + size(h.right) + 1;
return x;
}
请帮助我理解h=rotateLeft(h)
如何在三个节点中为顶级节点而不是中间节点提供两个连续的红色左侧链接。
答案 0 :(得分:0)
我终于明白了算法是如何工作的。在h=rotateLeft(h)
之后,第二个和第三个if statements
评估为false
。并返回h
。在递归的一级,我们得到h.left =h
,其中h
位于等式的左边,是三个节点中的顶级节点,具有两个连续的红色左链接。然后第一个if
语句的计算结果为false,第二个if
语句的计算结果为true,我们右旋转,然后我们进行翻转颜色。
如果我错了,请纠正我。