基本算法连载(3)-红黑树

什么是红黑树?
“Being Partly balanced can be good enough”,红黑树并不追求“完全平衡”——它只要求部分地达到平衡,降低了对旋转的要求,从而提高了性能。


红黑树的性质
A binary search tree is a red-black tree if:
   1. A node is either red or black.
   2. The root is black.
   3. All leaves are black. (This includes the NIL children)
   4. Both children of every red node are black. (and by implication every red node must have a black parent.)
   5. All paths from any given node to its leaf nodes contain the same number of black nodes.

由以上所给出的约束,可以得到红黑树关键性质: 从根到叶子的最长的可能路径不多于最短的可能路径的两倍长。对红黑树进行各种操作时必须保证这些约束条件不被破坏!


红黑树 vs AVL
红黑树算法的时间复杂度和AVL相同,但统计性能比AVL树更高。具体怎样,可以看以下这段描述:
AVL trees are actually easier to implement than RB trees because there are fewer cases.  And AVL trees require O(1) rotations on an insertion, whereas red-black trees require O(lg n).
In practice, the speed of AVL trees versus red-black trees will depend on the data that you're inserting.  If your data is well distributed, so that an unbalanced binary tree would generally be acceptable (i.e. roughly in random order), but you want to handle bad cases anyway, then red-black trees will be faster because they do less unnecessary rebalancing of already acceptable data.On the other hand, if a pathological insertion order (e.g. increasing order of key) is common, then AVL trees will be faster, because the stricter balancing rule will reduce the tree's height.
Splay trees might be even faster than either RB or AVL trees,depending on your data access distribution.  And if you can use a hash instead of a tree, then that'll be fastest of all.

学习之后的感受
1、看数据结构,非常重要的一点是了解它们的性能。知道它们各自与竞争对手相比,强在何处,弱在哪里。
2、设计这种数据结构,出发点在哪里,也就是为什么需要它。
 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值