我无法在两个节点(Parent_Node和Grand_Parent_Node)之间交换颜色。
插入正确,仅对节点着色不正确。 实际上,除了根节点之外,整个树没有其他颜色。 RedBlack Tree Java实现。取自GeeksForGeeks,并从C ++转换为Java。
public class RB {
Node root;
enum Color {RED, BLACK;}
public class Node {
int data;
Color color;
Node left, right, parent;
// Constructor
Node(int data) {
this.data = data;
left = right = parent = null;
}
}
// This function fixes violations caused by BST insertion
void fixViolation(Node root, Node pt) {
Node parent_pt = null;
Node grand_parent_pt = null;
while ((pt != root) && (pt.color != Color.BLACK) && (pt.parent.color == Color.RED)) {
parent_pt = pt.parent;
grand_parent_pt = pt.parent.parent;
/* Case : A
Parent of pt is left child of Grand-parent of pt */
if (parent_pt == grand_parent_pt.left) {
Node uncle_pt = grand_parent_pt.right;
/* Case : 1
The uncle of pt is also red
Only Recoloring required */
if (uncle_pt != null && uncle_pt.color == Color.RED) {
grand_parent_pt.color = Color.RED;
parent_pt.color = Color.BLACK;
uncle_pt.color = Color.BLACK;
pt = grand_parent_pt;
} else {
/* Case : 2
pt is right child of its parent
Left-rotation required */
if (pt == parent_pt.right) {
rotateLeft(root, parent_pt);
pt = parent_pt;
parent_pt = pt.parent;
}
/* Case : 3
pt is left child of its parent
Right-rotation required */
rotateRight(root, grand_parent_pt);
swap(parent_pt.color, grand_parent_pt.color);
pt = parent_pt;
}
}
/* Case : B
Parent of pt is right child of Grand-parent of pt */
else {
Node uncle_pt = grand_parent_pt.left;
/* Case : 1
The uncle of pt is also red
Only Recoloring required */
if ((uncle_pt != null) && (uncle_pt.color == Color.RED)) {
grand_parent_pt.color = Color.RED;
parent_pt.color = Color.BLACK;
uncle_pt.color = Color.BLACK;
pt = grand_parent_pt;
} else {
/* Case : 2
pt is left child of its parent
Right-rotation required */
if (pt == parent_pt.left) {
rotateRight(root, parent_pt);
pt = parent_pt;
parent_pt = pt.parent;
}
/* Case : 3
pt is right child of its parent
Left-rotation required */
rotateLeft(root, grand_parent_pt);
swap(parent_pt.color, grand_parent_pt.color);
pt = parent_pt;
}
}
}
root.color = Color.BLACK;
}
void swap(Color color, Color color2) {
// TODO Auto-generated method stub
Color temp;
temp = color;
color = color2;
color2 = temp;
}
}
不包括主要功能和BST插入功能。