Skip to content

Commit a5c6001

Browse files
committed
polynomial solution for vertex coever
1 parent 17a43bd commit a5c6001

2 files changed

Lines changed: 87 additions & 0 deletions

File tree

‎src/ds/RedBlackTree.java‎

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
package ds;
2+
3+
/**
4+
* Created by sherxon on 3/20/17.
5+
*/
6+
public class RedBlackTree<K extends Comparable, V> {
7+
RBNode root;
8+
9+
public void put(K key, V value) {
10+
if (root == null) {
11+
root = new RBNode(key, value, false);
12+
} else {
13+
putRecursive(root, key, value);
14+
}
15+
}
16+
17+
private RBNode putRecursive(RBNode x, K key, V value) {
18+
if (x == null) return new RBNode(key, value);
19+
if (isBlack(x) && isRed(x.left) && isRed(x.right)) {
20+
// flip color
21+
x.isRed = true;
22+
x.left.isRed = false;
23+
x.left.isRed = false;
24+
}
25+
if (x.key.compareTo(key) > 0)
26+
x.left = putRecursive(root.left, key, value);
27+
else if (x.key.compareTo(key) < 0)
28+
x.right = putRecursive(root.right, key, value);
29+
else x.value = value;
30+
return x;
31+
}
32+
33+
private boolean isRed(RBNode x) {
34+
return x != null && x.isRed;
35+
}
36+
37+
private boolean isBlack(RBNode x) {
38+
return x != null && !x.isRed;
39+
}
40+
41+
public V get(K key) {
42+
if (key == null || root == null) return null;
43+
return getRecursive(root, key);
44+
}
45+
46+
private V getRecursive(RBNode root, K key) {
47+
if (root == null) return null;
48+
if (root.key.compareTo(key) > 0)
49+
return getRecursive(root.left, key);
50+
else if (root.key.compareTo(key) < 0)
51+
return getRecursive(root.right, key);
52+
else return root.value;
53+
}
54+
55+
56+
private class RBNode {
57+
K key;
58+
V value;
59+
RBNode left, right, parent;
60+
boolean isRed;
61+
62+
public RBNode(K key, V value) {
63+
this.key = key;
64+
this.value = value;
65+
}
66+
67+
public RBNode(K key, V value, boolean isRed) {
68+
this.key = key;
69+
this.value = value;
70+
this.isRed = isRed;
71+
}
72+
73+
public RBNode(K key, V value, RBNode parent) {
74+
this.key = key;
75+
this.value = value;
76+
this.parent = parent;
77+
}
78+
}
79+
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
package ds.graph.vertexcover;
2+
3+
/**
4+
* Created by sherxon on 3/21/17.
5+
*/
6+
public class PolynomialSolutionForVertexCover {
7+
8+
}

0 commit comments

Comments
 (0)