红黑树平衡了吗

编程入门 行业动态 更新时间:2024-10-18 14:18:58
本文介绍了红黑树平衡了吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在研究红黑树,正在阅读Cormen的算法简介这本书。现在,我尝试使用书中描述的伪代码RB-INSERT-FIXUP(T,z)创建数字1-10的红黑树。这是屏幕快照

一切都很好,直到我在树中插入数字 6。根据伪代码,我得到以下结果

我可以手动执行 2和 4的左旋转过程并更改颜色。在那种情况下,我将得到以下结果,该结果是适当平衡的

所以我的问题是:

是不平衡的树?还是在插入节点期间错过了什么?

解决方案

这很好。红黑树是平衡的,但不一定完美。确切地说,红黑树的属性可确保到叶子的最长路径(隐式,未在图片中显示)最长为最短路径的两倍。最短的一个具有长度2(2-> 1->叶子),最长的一个具有长度4(2-> 4-> 5-> 6->叶子),因此不变量确实成立。

I am studying red-black trees and I am reading the Cormen's "Introduction to Algorithms" book. Now I am trying to create red-black tree with numbers 1-10 by using the pseudo-code described in the book - RB-INSERT-FIXUP(T, z). Here is the screenshot

Everything was fine until I inserted number "6" into the tree. According to pseudo-code I get the following result

As you can see all red-black tree requirements met, but I am confused because I know that red-black tree should be balanced on each step.

I can manually perform "left-rotate" procedure with "2" and "4" and change the colours. In that case I will get the following result, which is balanced appropriately

So my question is:

Is that all right to have unbalanced tree?, or I missed something during insertion nodes?

解决方案

This is fine. Red-black trees are balanced, but not necessarily perfectly. To be precise, properties of red-black tree guarantee that the longest path to the leaf (implicit, not shown in your picture) is at most twice as long as the shortest. Shortest one has length 2 (2 -> 1 -> leaf), longest one has length 4 (2 -> 4 -> 5 -> 6 -> leaf), so the invariant does hold.

更多推荐

红黑树平衡了吗

本文发布于:2023-11-30 08:12:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649316.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:红黑

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!