zoukankan      html  css  js  c++  java
  • Red-Black Tree

    Diagram of binary tree. The black root node has two red children and four black grandchildren. The child nodes of the grandchildren are black nil pointers or red nodes with black nil pointers.
    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
    Recoloring
     
  • 相关阅读:
    单元测试
    python gdb
    圣诞树
    网络是怎样连接的 读书笔记
    POJ2104 K-th Number(整体二分)
    [SDOI2011]消耗战
    [HNOI2011]XOR和路径
    [HNOI2013]游走
    [JSOI2008]球形空间产生器
    POJ2728 Desert King
  • 原文地址:https://www.cnblogs.com/joycelee/p/4518685.html
Copyright © 2011-2022 走看看