Skip to content

Commit 0ab1114

Browse files
authored
Add nearest right neighbor (TheAlgorithms#2574)
1 parent ad380dc commit 0ab1114

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed
+84
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
package DataStructures.NRKTrees;
2+
3+
import java.util.Scanner;
4+
import java.util.concurrent.ThreadLocalRandom;
5+
6+
class Main {
7+
8+
public static void main(String[] args) {
9+
NRKTree root = BuildTree();
10+
Scanner sc = new Scanner(System.in);
11+
System.out.print("Enter first number: ");
12+
int inputX0 = sc.nextInt();
13+
int toPrint = nearestRightKey(root, inputX0);
14+
System.out.println("Key: " + toPrint);
15+
}
16+
17+
public static NRKTree BuildTree() {
18+
int randomX = ThreadLocalRandom.current().nextInt(0, 100 + 1);
19+
NRKTree root = new NRKTree(null, null, randomX);
20+
21+
for (int i = 0; i < 1000; i++) {
22+
randomX = ThreadLocalRandom.current().nextInt(0, 100 + 1);
23+
root = root.insertKey(root, randomX);
24+
}
25+
26+
return root;
27+
}
28+
29+
public static int nearestRightKey(NRKTree root, int x0) {
30+
//Check whether tree is empty
31+
if(root == null){
32+
return 0;
33+
}
34+
else {
35+
if(root.data - x0 > 0){
36+
// Go left
37+
int temp = nearestRightKey(root.left, x0);
38+
if(temp == 0){
39+
return root.data;
40+
}
41+
return temp;
42+
} else {
43+
// Go right
44+
return nearestRightKey(root.right, x0);
45+
}
46+
47+
}
48+
}
49+
50+
}
51+
52+
53+
class NRKTree {
54+
55+
public NRKTree left;
56+
public NRKTree right;
57+
public int data;
58+
59+
public NRKTree(int x) {
60+
this.left = null;
61+
this.right = null;
62+
this.data = x;
63+
}
64+
65+
public NRKTree(NRKTree right, NRKTree left, int x) {
66+
this.left = left;
67+
this.right = right;
68+
this.data = x;
69+
}
70+
71+
public NRKTree insertKey(NRKTree current, int value) {
72+
if (current == null) {
73+
return new NRKTree(value);
74+
}
75+
76+
if (value < current.data) {
77+
current.left = insertKey(current.left, value);
78+
} else if (value > current.data) {
79+
current.right = insertKey(current.right, value);
80+
}
81+
82+
return current;
83+
}
84+
}

0 commit comments

Comments
 (0)