为什么RB-Tree不能是列表?

发布于 2024-08-29 22:24:58 字数 405 浏览 3 评论 0原文

我的 rb 树有问题。根据维基百科,rb-tree 需要遵循以下规则:

  1. 节点要么是红色,要么是黑色。
  2. 根是黑色的。 (这条规则在某些定义中使用,而在其他定义中则不使用。由于根总是可以从红色变为黑色,但不一定反之亦然,因此该规则对分析影响不大。)
  3. 所有叶子都是黑色的。
  4. 每个红色节点的两个子节点都是黑色的。
  5. 从给定节点到其任何后代叶子的每条简单路径都包含相同数量的黑色节点。

众所周知,rb 树需要平衡,并且高度为 O(log(n))。 但是,如果我们插入一系列递增的数字(1,2,3,4,5...),理论上我们将得到一棵看起来像列表的树,其高度为 O(n) 及其所有节点黑色,这与上面提到的 rb-tree 属性并不矛盾。那么,我哪里错了??

谢谢。

I have a problem with the rb-trees. according to wikipedia, rb-tree needs to follow the following:

  1. A node is either red or black.
  2. The root is black. (This rule is used in some definitions and not others. Since the root can always be changed from red to black but not necessarily vice-versa this rule has little effect on analysis.)
  3. All leaves are black.
  4. Both children of every red node are black.
  5. Every simple path from a given node to any of its descendant leaves contains the same number of black nodes.

As we know, an rb-tree needs to be balanced and has the height of O(log(n)).
But, if we insert an increasing series of numbers (1,2,3,4,5...) and theoretically we will get a tree that will look like a list and will have the height of O(n) with all its nodes black, which doesn't contradict the rb-tree properties mentioned above. So, where am I wrong??

thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一生独一 2024-09-05 22:24:58

您的示例与属性号 5 相矛盾,因此它不是有效的红黑树。

我们拥有的树是:

b(1, nil, b(2, nil, b(3, nil, b(4, nil, b(5, nil, nil)))))

因此,为了到达最后两个叶子(节点 5 的子节点),我们必须访问五个黑色节点(由每个 b 表示),要到达节点 4 下的叶子,我们必须访问四个黑色节点等。这意味着从根到某些包含不同数量黑色节点的后代有简单的路径,这会导致无效财产5.

Your example contradicts property number 5, so it's not a valid Red-Black tree.

The tree we have is:

b(1, nil, b(2, nil, b(3, nil, b(4, nil, b(5, nil, nil)))))

so to get to the last two leaves (the children of node 5), we have to visit five black nodes (represented by each b), to get to the leaf under node 4 we have to visit four black nodes, etc. That means that there are simple paths from the root to some of this descendants containing a different number of black nodes, which invalidates property 5.

世界等同你 2024-09-05 22:24:58

文章的进一步内容:

插入从添加节点开始
就像二叉搜索树插入一样
并将其染成红色

A bit further down in the article:

Insertion begins by adding the node
much as binary search tree insertion
does and by coloring it red.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文