红黑树伪代码冗余
在算法第三版简介中,他们有一个红黑树删除的伪代码实现。这里是...
RB-DELETE(T, z)
y = z
y-original-color = y.color
if z.left == T.nil
x = z.right
RB-TRANSPLANT(T, z, z.right)
elseif z.right == T.nil
x = z.left
RB-TRANSPLANT(T, z, z.left)
else
y = TREE-MINIMUM(z.right)
y-original-color = y.color
x = y.right
if y.p == z
x.p = y // <--------- why????
else
RB-TRANSPLANT(T, y, y.right)
y.right = z.right
y.right.p = y
RB-TRANSPLANT(T, z, y)
y.left = z.left
y.left.p = y
y.color = z.color
if y-original-color == BLACK
RB-DELETE-FIXUP(T, x)
TREE-MINIMUM 只是查找树中的最小值,RB-TRANSPLANT 获取第二个参数的父级并使其指向第三个参数,并使第三个参数的父级作为第二个参数的父级。
根据我的评论,他们测试 yp 是否为 z,如果是,则将 xp 设置为 y。但是 x 已经是 y.right,所以这就像说 y.right.p = y,但是 y.right.p 已经是 y!他们为什么要这样做?
这是他们的解释...
“然而,当 y 的原始父节点是 z 时,我们不希望 xp 指向 y 的原始父节点,因为我们正在从树中删除该节点。因为节点 y 将向上移动以占据 z 在树中的位置,所以在第 13 行中将 xp 设置为 y 会导致 xp 指向 y 父节点的原始位置,即使 x == T.nil。”
所以他们想让 x 的父母成为 y...它已经是 y...
In introduction to Algorithms Third Edition they have a pseudocode implementation of red-black tree deletion. Here it is...
RB-DELETE(T, z)
y = z
y-original-color = y.color
if z.left == T.nil
x = z.right
RB-TRANSPLANT(T, z, z.right)
elseif z.right == T.nil
x = z.left
RB-TRANSPLANT(T, z, z.left)
else
y = TREE-MINIMUM(z.right)
y-original-color = y.color
x = y.right
if y.p == z
x.p = y // <--------- why????
else
RB-TRANSPLANT(T, y, y.right)
y.right = z.right
y.right.p = y
RB-TRANSPLANT(T, z, y)
y.left = z.left
y.left.p = y
y.color = z.color
if y-original-color == BLACK
RB-DELETE-FIXUP(T, x)
TREE-MINIMUM just finds the smallest value in a tree, RB-TRANSPLANT takes the parent of the second parameter and has it point to the third parameter, and has the third parameter's parent be the second parameter's parent.
By my comment, they test if y.p is z and if so set x.p to y. But x is already y.right, so this is like saying y.right.p = y, but y.right.p is already y! Why are they doing this?
Here is their explanation...
“When y's original parent is z, however, we do not want x.p to point to y's original parent, since we are removing that node from the tree. Because node y will move up to take z's position in the tree, setting x.p to y in line 13 causes x.p to point to the original position of y's parent, even if x == T.nil.”
So they want to keep x's parent to be y...it already is y...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
他们在文本中指出 x 也可以为 Nil,即当 y.right 为 Nil 时。看来 Nil 在此代码中也由节点表示,并且他们不想留下悬空指针。
They state in the text that x can be also Nil, i.e. when y.right is Nil. It seems Nil is in this code also represented by a node, and they don't want to leave a dangling pointer.