Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 21.3k
Expand file tree
/
Copy pathnearestRightKey.java
More file actions
Latest commit
83 lines (69 loc) · 2.11 KB
/
Copy pathnearestRightKey.java
File metadata and controls
83 lines (69 loc) · 2.11 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
packagecom.thealgorithms.datastructures.trees;
importjava.util.Scanner;
importjava.util.concurrent.ThreadLocalRandom;
finalclassNearestRightKey {
privateNearestRightKey() {
}
publicstaticvoidmain(String[] args) {
NRKTreeroot = buildTree();
Scannersc = newScanner(System.in);
System.out.print("Enter first number: ");
intinputX0 = sc.nextInt();
inttoPrint = nearestRightKey(root, inputX0);
System.out.println("Key: " + toPrint);
sc.close();
}
publicstaticNRKTreebuildTree() {
intrandomX = ThreadLocalRandom.current().nextInt(0, 100 + 1);
NRKTreeroot = newNRKTree(null, null, randomX);
for (inti = 0; i < 1000; i++) {
randomX = ThreadLocalRandom.current().nextInt(0, 100 + 1);
root = root.insertKey(root, randomX);
}
returnroot;
}
publicstaticintnearestRightKey(NRKTreeroot, intx0) {
// Check whether tree is empty
if (root == null) {
return0;
} else {
if (root.data - x0 > 0) {
// Go left
inttemp = nearestRightKey(root.left, x0);
if (temp == 0) {
returnroot.data;
}
returntemp;
} else {
// Go right
returnnearestRightKey(root.right, x0);
}
}
}
}
classNRKTree {
publicNRKTreeleft;
publicNRKTreeright;
publicintdata;
NRKTree(intx) {
this.left = null;
this.right = null;
this.data = x;
}
NRKTree(NRKTreeright, NRKTreeleft, intx) {
this.left = left;
this.right = right;
this.data = x;
}
publicNRKTreeinsertKey(NRKTreecurrent, intvalue) {
if (current == null) {
returnnewNRKTree(value);
}
if (value < current.data) {
current.left = insertKey(current.left, value);
} elseif (value > current.data) {
current.right = insertKey(current.right, value);
}
returncurrent;
}
}