-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGetRankBST.java
More file actions
69 lines (61 loc) · 1.38 KB
/
GetRankBST.java
File metadata and controls
69 lines (61 loc) · 1.38 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
package ds;
/**
* Design a data structure using which we can calculate rank of a number very
* fast.
*
* @author shivam.maharshi
*/
public class GetRankBST {
GetRankBST left;
GetRankBST right;
int value;
int childCount;
public GetRankBST(int value) {
this.value = value;
this.childCount = 0;
}
public void insert(GetRankBST root, int value) {
while (true) {
if (value > root.value) {
root.childCount++;
if (root.right == null) {
root.right = new GetRankBST(value);
} else {
insert(root.right, value);
}
return;
} else {
root.childCount++;
if (root.left == null) {
root.left = new GetRankBST(value);
} else {
insert(root.left, value);
}
return;
}
}
}
public int getRank(GetRankBST root, int value) {
if (root == null) {
// Not present.
return -1;
}
if (root.value == value)
return getChildCount(root.left) + 2;
if (value < root.value) {
return getRank(root.left, value);
} else {
return getChildCount(root.left) + getRank(root.right, value);
}
}
public int getChildCount(GetRankBST node) {
if (node == null)
return -1;
return node.childCount;
}
public static void main(String[] args) {
GetRankBST root = new GetRankBST(100);
root.insert(root, 50);
System.out.println(root.getRank(root, 50));
}
}