【问题标题】:Left rotation in red black trees红黑树左旋
【发布时间】:2013-11-11 05:28:54
【问题描述】:

我一直在研究 Robert Sedgewick 在算法中描述的红黑树。下面是插入红黑树的代码。

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-node 的中间时。我们必须执行三个 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)如何在三个节点中给出顶部节点而不是中间节点,并带有两个连续的红色左链接。

【问题讨论】:

  • 您可以裁剪图像以显示可视化,除非文本很重要。
  • 文本不重要。我将裁剪图像。

标签: java algorithm red-black-tree


【解决方案1】:

我终于明白算法是如何工作的了。在h=rotateLeft(h) 之后,第二个和第三个if statements 评估为false。并返回 h。递归的上一层,我们得到h.left =h,其中等式左边的h 是三个节点中具有两个连续红色左链接的顶级节点。然后第一个if 语句评估为false,第二个if 语句评估为true,我们进行右旋转,然后我们进行颜色翻转。

如果我错了,请纠正我。

【讨论】:

    猜你喜欢
    • 2012-11-01
    • 2021-05-22
    • 2018-11-07
    • 2013-10-13
    • 1970-01-01
    • 2012-11-30
    • 2010-09-06
    • 2016-09-26
    • 1970-01-01
    相关资源
    最近更新 更多