码迷,mamicode.com
首页 > 其他好文 > 详细

Red-Black Tree

时间:2017-12-31 12:56:54      阅读:242      评论:0      收藏:0      [点我收藏+]

标签:rap   ica   资料   most   time   led   child   amp   because   

一、what is red-black tree

red–black tree is a kind of self-balancing binary search tree in computer science. Each node of the binary tree has an extra bit, and that bit is often interpreted as the color (red or black) of the node. These color bits are used to ensure the tree remains approximately balanced during insertions and deletions.[2]

Balance is preserved by painting each node of the tree with one of two colors in a way that satisfies certain properties, which collectively constrain how unbalanced the tree can become in the worst case. When the tree is modified, the new tree is subsequently rearranged and repainted to restore the coloring properties. The properties are designed in such a way that this rearranging and recoloring can be performed efficiently.

The balancing of the tree is not perfect, but it is good enough to allow it to guarantee searching in O(log n) time, where n is the total number of elements in the tree. The insertion and deletion operations, along with the tree rearrangement and recoloring, are also performed in O(log n) time.[3]

Tracking the color of each node requires only 1 bit of information per node because there are only two colors. The tree does not contain any other data specific to its being a red–black tree so its memory footprint is almost identical to a classic (uncolored) binary search tree. In many cases, the additional bit of information can be stored at no additional memory cost.

From wikipedia

 

二、basic of red-black tree 

技术分享图片

 

In addition to the requirements imposed on a binary search tree the following must be satisfied by a red–black tree:[16]

  1. Each node is either red or black.
  2. The root is black. This rule is sometimes omitted. 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 (NIL) are black.
  4. If a node is red, then both its children are black.
  5. Every path from a given node to any of its descendant NIL nodes contains the same number of black nodes. Some definitions: the number of black nodes from the root to a node is the node‘s black depth; the uniform number of black nodes in all paths from root to the leaves is called the black-height of the red–black tree.[17]

From wikipedia

 

三、violation

case1:

技术分享图片

case 2:

技术分享图片

case 3:

技术分享图片

三、Example

insert 1 2 3 4 5 6 to the RB-Tree

 

技术分享图片

 技术分享图片

 技术分享图片

技术分享图片

 四、参考资料

Red Black Tree - Part0

Red Black Tree - Part1

Red Black Tree - wikipedia

教你初步了解红黑树

教你透彻了解红黑树

红黑树(一)之 原理和算法详细介绍

 

Red-Black Tree

标签:rap   ica   资料   most   time   led   child   amp   because   

原文地址:https://www.cnblogs.com/yingbing/p/8157309.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!