A [b]red-black tree[/b] is a binary search tree with one extra bit of storage per node: its color, which can be either RED or BLACK.
红黑树性质:
1. The root is black.
2. If a node is red, then both its children are black.
3. For each node, all simple paths from the node to descendant leaves contain the same number of black nodes.
从根到叶子的最长的可能路径不多于最短的可能路径的两倍长,使得红黑树大致上是平衡的。
[b]rotation操作[/b]
[img]http://dl.iteye.com/upload/picture/pic/89648/ac6f2249-f56b-3132-ba8b-eef9dea08cf8.bmp[/img]
[b]插入[/b]
1. 先将新节点像BST的插入那样插入,将新节点标记为红色。(如果新节点的父亲为黑色就不用调整了)
2. 然后从该节点开始,依次向上进行颜色调整,直到父亲节点为黑色(即达到满足红黑树性质的状态)。
向上颜色调整规则(z为新节点,y为z父亲节点的兄弟)
[img]http://dl.iteye.com/upload/picture/pic/89650/39bd3e54-1217-3c7d-9990-f57bf86f5707.bmp[/img]
Case 1: z’s uncle y is red (whether z is left or right child)
[img]http://dl.iteye.com/upload/picture/pic/89652/0ef674b1-b119-3d86-83e4-4f96b1061459.bmp[/img]
Case 2: z’s uncle y is black and z is a right child
Case 3: z’s uncle y is black and z is a left child
插入已让我很晕,删除更为复杂,还是算了···
更多参看《算法导论》
红黑树性质:
1. The root is black.
2. If a node is red, then both its children are black.
3. For each node, all simple paths from the node to descendant leaves contain the same number of black nodes.
从根到叶子的最长的可能路径不多于最短的可能路径的两倍长,使得红黑树大致上是平衡的。
[b]rotation操作[/b]
[img]http://dl.iteye.com/upload/picture/pic/89648/ac6f2249-f56b-3132-ba8b-eef9dea08cf8.bmp[/img]
[b]插入[/b]
1. 先将新节点像BST的插入那样插入,将新节点标记为红色。(如果新节点的父亲为黑色就不用调整了)
2. 然后从该节点开始,依次向上进行颜色调整,直到父亲节点为黑色(即达到满足红黑树性质的状态)。
向上颜色调整规则(z为新节点,y为z父亲节点的兄弟)
[img]http://dl.iteye.com/upload/picture/pic/89650/39bd3e54-1217-3c7d-9990-f57bf86f5707.bmp[/img]
Case 1: z’s uncle y is red (whether z is left or right child)
[img]http://dl.iteye.com/upload/picture/pic/89652/0ef674b1-b119-3d86-83e4-4f96b1061459.bmp[/img]
Case 2: z’s uncle y is black and z is a right child
Case 3: z’s uncle y is black and z is a left child
插入已让我很晕,删除更为复杂,还是算了···
更多参看《算法导论》