-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRedBlackTree.java
More file actions
89 lines (73 loc) · 1.97 KB
/
RedBlackTree.java
File metadata and controls
89 lines (73 loc) · 1.97 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
public class RedBlackTree {
private static final boolean RED = true;
private static final boolean BLACK = false;
private Node root;
private class Node {
int key;
Node left;
Node right;
boolean color;
Node(int key) {
this.key = key;
this.color = RED;
}
}
// Other methods and constructors can be added here
// Insert a key into the Red-Black Tree
public void insert(int key) {
root = insert(root, key);
root.color = BLACK;
}
private Node insert(Node node, int key) {
if (node == null) {
return new Node(key);
}
if (key < node.key) {
node.left = insert(node.left, key);
} else if (key > node.key) {
node.right = insert(node.right, key);
} else {
// Key already exists, do nothing
return node;
}
if (isRed(node.right) && !isRed(node.left)) {
node = rotateLeft(node);
}
if (isRed(node.left) && isRed(node.left.left)) {
node = rotateRight(node);
}
if (isRed(node.left) && isRed(node.right)) {
flipColors(node);
}
return node;
}
// Check if a node is red
private boolean isRed(Node node) {
if (node == null) {
return false;
}
return node.color == RED;
}
// Perform a left rotation
private Node rotateLeft(Node node) {
Node x = node.right;
node.right = x.left;
x.left = node;
x.color = node.color;
node.color = RED;
return x;
}
private Node rotateRight(Node node) {
Node x = node.left;
node.left = x.right;
x.right = node;
x.color = node.color;
node.color = RED;
return x;
}
private void flipColors(Node node) {
node.color = RED;
node.left.color = BLACK;
node.right.color = BLACK;
}
}