forked from sherxon/AlgoDS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRedBlackTree.java
More file actions
104 lines (90 loc) · 2.75 KB
/
Copy pathRedBlackTree.java
File metadata and controls
104 lines (90 loc) · 2.75 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
package ds;
import java.util.Arrays;
import java.util.stream.Collectors;
/**
* Created by sherxon on 3/20/17.
*/
public class RedBlackTree<K extends Comparable, V> {
RBNode root;
public void put(K key, V value) {
if (root == null) {
root = new RBNode(key, value, false);
} else {
putRecursive(root, key, value);
}
}
private RBNode putRecursive(RBNode x, K key, V value) {
if (x == null) return new RBNode(key, value);
if (isBlack(x) && isRed(x.left) && isRed(x.right)) {
// flip color
x.isRed = true;
x.left.isRed = false;
x.left.isRed = false;
}
if (x.key.compareTo(key) > 0)
x.left = putRecursive(root.left, key, value);
else if (x.key.compareTo(key) < 0)
x.right = putRecursive(root.right, key, value);
else x.value = value;
String s = "";
s = Arrays.stream(s.split("\\s+")).collect(Collectors.joining(" "));
return x;
}
void rightRotate(RBNode root, boolean changeColor) {
RBNode parent = root.parent;
root.parent = parent.parent;
if (parent.parent != null) {
if (parent.parent.right == parent) {
parent.parent.right = root;
} else
parent.parent.left = root;
}
RBNode right = root.right;
root.right = parent;
parent.parent = root;
parent.left = right;
if (right != null) right.parent = parent;
if (changeColor) {
root.isRed = false;
parent.isRed = true;
}
}
private boolean isRed(RBNode x) {
return x != null && x.isRed;
}
private boolean isBlack(RBNode x) {
return x != null && !x.isRed;
}
public V get(K key) {
if (key == null || root == null) return null;
return getRecursive(root, key);
}
private V getRecursive(RBNode root, K key) {
if (root == null) return null;
if (root.key.compareTo(key) > 0)
return getRecursive(root.left, key);
else if (root.key.compareTo(key) < 0)
return getRecursive(root.right, key);
else return root.value;
}
private class RBNode {
K key;
V value;
RBNode left, right, parent;
boolean isRed;
public RBNode(K key, V value) {
this.key = key;
this.value = value;
}
public RBNode(K key, V value, boolean isRed) {
this.key = key;
this.value = value;
this.isRed = isRed;
}
public RBNode(K key, V value, RBNode parent) {
this.key = key;
this.value = value;
this.parent = parent;
}
}
}