gpt4 book ai didi

algorithm - 红黑树删除未知行为

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:39:12 27 4
gpt4 key购买 nike

我向一棵红黑树输入了几个数字。 (41; 38; 31;12; 19; 8)删除8和12(第一个截图)后,它进入了第二个截图的类型。我不明白为什么 31 变成红色。请帮我解决这个问题?如果可以,请提及与此相关的案例。谢谢!

最佳答案

如果你在Wikipedia上查看删除算法的解释,您可以将它们的节点命名映射到您的树,如下所示:

M = 0012,要移除的黑色节点
C = 0012 以下的 NIL 叶子(NIL 总是被认为是黑色的)

文章接着说了你的实际情况:

The complex case is when both M and C are black. [...] We begin by replacing M with its child C. [...] We will relabel this child C (in its new position) N, and its sibling (its new parent's other child) S [...] we will also use P for N's new parent, SL for S's left child, and SR for S's right child

所以现在我们在移除之后,但在重新着色之前:

enter image description here

P = 0019(红色)
N = NIL 叶子,0019 的左 child
S = 0031,0019的右 child

描述确定了几个案例,手头的案例是以下一个:

Case 4: S and S's children are black, but P is red. In this case, we simply exchange the colors of S and P.

解释了这种颜色交换的原因:

This does not affect the number of black nodes on paths going through S, but it does add one to the number of black nodes on paths going through N, making up for the deleted black node on those paths.

回想一下,在红黑树中必须维护这个不变量(property 5):

Every path from a given node to any of its descendant NIL nodes contains the same number of black nodes.

如果省略上述颜色交换,就会违反此不变量。

关于algorithm - 红黑树删除未知行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53665271/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com