iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 24
0
自我挑戰組

資料結構大便當系列 第 24

[Day 24] Red–Black Tree II

  • 分享至 

  • xImage
  •  

紅黑樹(Red–Black Tree)

Case

  • z's uncle y 為紅色

https://ithelp.ithome.com.tw/upload/images/20191006/20120250Y9KjhlBCaf.png

  • z's uncle y 是黑色,且 z 為右子節點
  • z's uncle y 是黑色,且 z 為左子節點

https://ithelp.ithome.com.tw/upload/images/20191006/20120250u5cyrPpP5n.png

  • 綜合狀況

https://ithelp.ithome.com.tw/upload/images/20191006/20120250ovljnNIrlV.png

Insert a key to Red–Black Tree

RB-INSERT

RB-INSERT(T, z)
    y = T.nil
    x = T.root
    whlie x != T.nil
        y = x
        if z.key < x.key
            x = x.left
        else
            x = x.right
        z.p = y
        if y == T.nil
            T.root = z
        elseif z.key < y.key
            y.left = z
        else y.right = z
        z.left = T.nil
        z.right = T.nil
        z.color = RED
        RB-INSERT-FIXUP(T, z)

RB-INSERT-FIXUP

RB-INSERT=FIXUP(T, z)
    while z.p.color == RED
        if z.p == z.p.p.left
            y = z.p.p.right
            if y.color = RED
                z.p.color = BLACK
                y.color = BLACK
                z.p.p.color = RED
                z = z.p.p
            else if z == z.p.right
                z = z.p
                LEFT-ROTATE(T,z)
                z.p.color = BLACK
                z.p.p.color = RED
                RIGHT-ROTATE(T, z.p.p)
       else (same as then clause with "right" and "left" exchanged)
   T.root.color = BLACK

上一篇
[Day 23] Red–Black Tree I
下一篇
[Day 25] Red–Black Tree III
系列文
資料結構大便當30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言