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

Red-Black Tree

时间:2015-05-21 07:50:59      阅读:100      评论:0      收藏:0      [点我收藏+]

标签:

技术分享
1. Every 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.)
3. There are no 2 adjacent red nodes.
4. Every path from a given node to any of its descendant NIL nodes contains the same number of black nodes.
 
Lemma
A red-black tree with n internal nodes has the height at most 2log(n+1)
 
Proof of the balance
A simple example to understand balancing is, a chain of 3 nodes is not possible in Red Black Tree
A chain of 3 nodes is nodes is not possible in Red-Black Trees. 
Following are NOT Red-Black Trees
        30             30               30       
       / \            /  \             /       20  NIL         20   NIL         20   NIL
    / \             / \              /  \   
  10  NIL          10  NIL          10  NIL
 
Operation
insert / delete / lookup / print —— in O(log N) worst-case time
 
ps : Rotate - O(1)
left_rotate & right_rotate
 
技术分享
 
 
1. insert - O(log N)
[step1] use the BST insert algorithm to add K to the tree — O(log N)
[step2] color the node containing K red
[step3] restore red-black tree properties (if necessary) — worst case, O(log N)
 
case 1 > K’s parent P is black, OK !
case 2 > K’s parent P is red, there will be 4+4 cases
 
first 4 cases, P’s sibling is NIL or black — change G to red!
<1> G.left = P, P.left = K  —  left rotate
技术分享
<2> G.left = P, P.right = K  —  change color and K to root
技术分享
<3> G.right = P, P.left = K  —  change color and K to root
技术分享
<4> G.right = P, P.right = K
技术分享
 
second 4 cases, P’s sibling is red — recolor all the way up
技术分享
 

Red-Black Tree

标签:

原文地址:http://www.cnblogs.com/joycelee/p/4518685.html

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