-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathredblack
More file actions
112 lines (96 loc) · 3.19 KB
/
Copy pathredblack
File metadata and controls
112 lines (96 loc) · 3.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
class RBNode {
int data;
RBNode left, right, parent;
boolean color; // true = RED, false = BLACK
RBNode(int data) {
this.data = data;
color = true;
}
}
public class RedBlackTree {
private RBNode root;
private void rotateLeft(RBNode x) {
RBNode y = x.right;
x.right = y.left;
if (y.left != null) y.left.parent = x;
y.parent = x.parent;
if (x.parent == null) root = y;
else if (x == x.parent.left) x.parent.left = y;
else x.parent.right = y;
y.left = x;
x.parent = y;
}
private void rotateRight(RBNode y) {
RBNode x = y.left;
y.left = x.right;
if (x.right != null) x.right.parent = y;
x.parent = y.parent;
if (y.parent == null) root = x;
else if (y == y.parent.left) y.parent.left = x;
else y.parent.right = x;
x.right = y;
y.parent = x;
}
public void insert(int data) {
RBNode node = new RBNode(data);
root = bstInsert(root, node);
fixViolation(node);
}
private RBNode bstInsert(RBNode root, RBNode node) {
if (root == null) return node;
if (node.data < root.data) {
root.left = bstInsert(root.left, node);
root.left.parent = root;
} else {
root.right = bstInsert(root.right, node);
root.right.parent = root;
}
return root;
}
private void fixViolation(RBNode node) {
while (node != root && node.parent.color) {
RBNode parent = node.parent;
RBNode grandparent = parent.parent;
if (parent == grandparent.left) {
RBNode uncle = grandparent.right;
if (uncle != null && uncle.color) {
parent.color = false;
uncle.color = false;
grandparent.color = true;
node = grandparent;
} else {
if (node == parent.right) {
rotateLeft(parent);
node = parent;
parent = node.parent;
}
rotateRight(grandparent);
boolean temp = parent.color;
parent.color = grandparent.color;
grandparent.color = temp;
node = parent;
}
} else {
RBNode uncle = grandparent.left;
if (uncle != null && uncle.color) {
parent.color = false;
uncle.color = false;
grandparent.color = true;
node = grandparent;
} else {
if (node == parent.left) {
rotateRight(parent);
node = parent;
parent = node.parent;
}
rotateLeft(grandparent);
boolean temp = parent.color;
parent.color = grandparent.color;
grandparent.color = temp;
node = parent;
}
}
}
root.color = false;
}
}