紅黑樹的原理以及演算法見文章:
紅黑樹的節點定義:
package org.algorithm.redblacktree;
/*** created with intellij idea.
* user: qarkly
* date: 14-6-8
* time: 下午11:16
* to change this template use file | settings | file templates.
*/public class redblacknode
public redblacknode(byte color)
public redblacknode(comparable element,byte color)
}
左旋操作實現:
/**
* 左旋操作
* @param node
*/private void leftrotate(redblacknode node)else if(node == node.parent.left)else
pnode.left = node;
node.parent = pnode;
}
private void insert(redblacknode node)else if(node.element.compareto(curnode.element) >0)else}
node.parent = prenode;
if(prenode == redblacknode.nill)else if(node.element.compareto(prenode.element) < 0)else
node.left = node.right = redblacknode.nill;
node.color = redblacknode.red;
brinsertfixup(node);
}
插入修復演算法rb-insert-fixup現實:
private void brinsertfixup(redblacknode node)else
node.parent.color = redblacknode.black;
node.parent.parent.color = redblacknode.red;
rightrotate(node.parent.parent);
// node = node.parent;
}}elseelse
node.parent.color = redblacknode.black;
node.parent.parent.color = redblacknode.red;
leftrotate(node.parent.parent);
// node = node.parent;}}
}root.color = redblacknode.black;
}
紅黑樹的刪除實現rb-delete(t, z)
private redblacknode delete(redblacknode node)
redblacknode pnode;
if (node.left == redblacknode.nill || node.right == redblacknode.nill)else
redblacknode nnode;
if(pnode.left != redblacknode.nill)else
nnode.parent = pnode.parent;
if(pnode.parent == redblacknode.nill)elseelse}
if(pnode != node)
if(pnode.color == redblacknode.black )
return pnode;
}
刪除後的修復和保持操作rb-delete-fixup(t, x)
private void brdeletefixup(redblacknode node)
while (node != root && node.color == redblacknode.black)
if(bnode.left.color == redblacknode.black && bnode.right.color == redblacknode.black)else if(bnode.right.color == redblacknode.black)
bnode.color = node.parent.color;
node.parent.color = redblacknode.black;
bnode.right.color = redblacknode.black;
leftrotate(node.parent);
node = root;
}else
if(bnode.left.color == redblacknode.black && bnode.right.color == redblacknode.black)else if(bnode.left.color == redblacknode.black)
bnode.color = node.parent.color;
node.parent.color = redblacknode.black;
bnode.left.color = redblacknode.black;
rightrotate(node.parent);
node = root;}}
node.color = redblacknode.black;
}
文中**排版貌似不太好看,附上github的完整**
java實現紅黑樹
package com.lsl public class redblacktree 節點左旋方法,將當前節點變為其右子樹的左子樹 private void leftrotate redblacknode x y.parent x.parent 將x的父親變為y的父親 if x.parent null...
紅黑樹的Java實現
紅黑樹 red black tree,簡稱rb樹 是一種特殊的二叉查詢樹,所以他也滿足二叉查詢樹的特徵 任意乙個節點的值大於右子節點的鍵值,小於左子節點的鍵值。除此之外,紅黑樹還具備很多其他特徵 1 每個節點都是紅色或者黑色 2 根節點必定為黑色 3 每個葉節點 左右子節點都為null的節點 必定是...
紅黑樹下 紅黑樹的實現
1.實現紅黑樹的基本思想 實際上,紅黑樹是有固定的平衡過程的 遇到什麼樣的節點分布,我們就對應怎麼去調整。只要按照這些固定的調整規則來操作,就能將乙個非平衡的紅黑樹調整成平衡的。首先,我們需要再來看一下紅黑樹的定義 在插入 刪除節點的過程中,第 三 四點要求可能會被破壞,所以 平衡調整 實際上就是把...