-
Notifications
You must be signed in to change notification settings - Fork 19.8k
/
Copy pathKDTree.java
456 lines (412 loc) · 13.2 KB
/
KDTree.java
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
package com.thealgorithms.datastructures.trees;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Objects;
import java.util.Optional;
/*
* K-D Tree Implementation
* Wikipedia: https://en.wikipedia.org/wiki/K-d_tree
*
* Author: Amir Hosseini (https://github.com/itsamirhn)
*
* */
public class KDTree {
private Node root;
private final int k; // Dimensions of the points
/**
* Constructor for empty KDTree
*
* @param k Number of dimensions
*/
KDTree(int k) {
this.k = k;
}
/**
* Builds the KDTree from the specified points
*
* @param points Array of initial points
*/
KDTree(Point[] points) {
if (points.length == 0) {
throw new IllegalArgumentException("Points array cannot be empty");
}
this.k = points[0].getDimension();
for (Point point : points) {
if (point.getDimension() != k) {
throw new IllegalArgumentException("Points must have the same dimension");
}
}
this.root = build(points, 0);
}
/**
* Builds the KDTree from the specified coordinates of the points
*
* @param pointsCoordinates Array of initial points coordinates
*
*/
KDTree(int[][] pointsCoordinates) {
if (pointsCoordinates.length == 0) {
throw new IllegalArgumentException("Points array cannot be empty");
}
this.k = pointsCoordinates[0].length;
Point[] points = Arrays.stream(pointsCoordinates).map(Point::new).toArray(Point[] ::new);
for (Point point : points) {
if (point.getDimension() != k) {
throw new IllegalArgumentException("Points must have the same dimension");
}
}
this.root = build(points, 0);
}
static class Point {
int[] coordinates;
public int getCoordinate(int i) {
return coordinates[i];
}
public int getDimension() {
return coordinates.length;
}
Point(int[] coordinates) {
this.coordinates = coordinates;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Point other) {
return Arrays.equals(other.coordinates, this.coordinates);
}
return false;
}
@Override
public int hashCode() {
return Arrays.hashCode(coordinates);
}
@Override
public String toString() {
return Arrays.toString(coordinates);
}
/**
* Find the comparable distance between two points (without SQRT)
*
* @param p1 First point
* @param p2 Second point
*
* @return The comparable distance between the two points
*/
public static int comparableDistance(Point p1, Point p2) {
int distance = 0;
for (int i = 0; i < p1.getDimension(); i++) {
int t = p1.getCoordinate(i) - p2.getCoordinate(i);
distance += t * t;
}
return distance;
}
/**
* Find the comparable distance between two points with ignoring specified axis
*
* @param p1 First point
* @param p2 Second point
* @param axis The axis to ignore
*
* @return The distance between the two points
*/
public static int comparableDistanceExceptAxis(Point p1, Point p2, int axis) {
int distance = 0;
for (int i = 0; i < p1.getDimension(); i++) {
if (i == axis) {
continue;
}
int t = p1.getCoordinate(i) - p2.getCoordinate(i);
distance += t * t;
}
return distance;
}
}
static class Node {
private Point point;
private int axis; // 0 for x, 1 for y, 2 for z, etc.
private Node left = null; // Left child
private Node right = null; // Right child
Node(Point point, int axis) {
this.point = point;
this.axis = axis;
}
public Point getPoint() {
return point;
}
public Node getLeft() {
return left;
}
public Node getRight() {
return right;
}
public int getAxis() {
return axis;
}
/**
* Get the nearest child according to the specified point
*
* @param point The point to find the nearest child to
*
* @return The nearest child Node
*/
public Node getNearChild(Point point) {
if (point.getCoordinate(axis) < this.point.getCoordinate(axis)) {
return left;
} else {
return right;
}
}
/**
* Get the farthest child according to the specified point
*
* @param point The point to find the farthest child to
*
* @return The farthest child Node
*/
public Node getFarChild(Point point) {
if (point.getCoordinate(axis) < this.point.getCoordinate(axis)) {
return right;
} else {
return left;
}
}
/**
* Get the node axis coordinate of point
*
* @return The axis coordinate of the point
*/
public int getAxisCoordinate() {
return point.getCoordinate(axis);
}
}
public Node getRoot() {
return root;
}
/**
* Builds the KDTree from the specified points
*
* @param points Array of initial points
* @param depth The current depth of the tree
*
* @return The root of the KDTree
*/
private Node build(Point[] points, int depth) {
if (points.length == 0) {
return null;
}
int axis = depth % k;
if (points.length == 1) {
return new Node(points[0], axis);
}
Arrays.sort(points, Comparator.comparingInt(o -> o.getCoordinate(axis)));
int median = points.length >> 1;
Node node = new Node(points[median], axis);
node.left = build(Arrays.copyOfRange(points, 0, median), depth + 1);
node.right = build(Arrays.copyOfRange(points, median + 1, points.length), depth + 1);
return node;
}
/**
* Insert a point into the KDTree
*
* @param point The point to insert
*
*/
public void insert(Point point) {
if (point.getDimension() != k) {
throw new IllegalArgumentException("Point has wrong dimension");
}
root = insert(root, point, 0);
}
/**
* Insert a point into a subtree
*
* @param root The root of the subtree
* @param point The point to insert
* @param depth The current depth of the tree
*
* @return The root of the KDTree
*/
private Node insert(Node root, Point point, int depth) {
int axis = depth % k;
if (root == null) {
return new Node(point, axis);
}
if (point.getCoordinate(axis) < root.getAxisCoordinate()) {
root.left = insert(root.left, point, depth + 1);
} else {
root.right = insert(root.right, point, depth + 1);
}
return root;
}
/**
* Search for Node corresponding to the specified point in the KDTree
*
* @param point The point to search for
*
* @return The Node corresponding to the specified point
*/
public Optional<Node> search(Point point) {
if (point.getDimension() != k) {
throw new IllegalArgumentException("Point has wrong dimension");
}
return search(root, point);
}
/**
* Search for Node corresponding to the specified point in a subtree
*
* @param root The root of the subtree to search in
* @param point The point to search for
*
* @return The Node corresponding to the specified point
*/
public Optional<Node> search(Node root, Point point) {
if (root == null) {
return Optional.empty();
}
if (root.point.equals(point)) {
return Optional.of(root);
}
return search(root.getNearChild(point), point);
}
/**
* Find a point with minimum value in specified axis in the KDTree
*
* @param axis The axis to find the minimum value in
*
* @return The point with minimum value in the specified axis
*/
public Point findMin(int axis) {
return findMin(root, axis).point;
}
/**
* Find a point with minimum value in specified axis in a subtree
*
* @param root The root of the subtree to search in
* @param axis The axis to find the minimum value in
*
* @return The Node with minimum value in the specified axis of the point
*/
public Node findMin(Node root, int axis) {
if (root == null) {
return null;
}
if (root.getAxis() == axis) {
if (root.left == null) {
return root;
}
return findMin(root.left, axis);
} else {
Node left = findMin(root.left, axis);
Node right = findMin(root.right, axis);
Node[] candidates = {left, root, right};
return Arrays.stream(candidates).filter(Objects::nonNull).min(Comparator.comparingInt(a -> a.point.getCoordinate(axis))).orElse(null);
}
}
/**
* Find a point with maximum value in specified axis in the KDTree
*
* @param axis The axis to find the maximum value in
*
* @return The point with maximum value in the specified axis
*/
public Point findMax(int axis) {
return findMax(root, axis).point;
}
/**
* Find a point with maximum value in specified axis in a subtree
*
* @param root The root of the subtree to search in
* @param axis The axis to find the maximum value in
*
* @return The Node with maximum value in the specified axis of the point
*/
public Node findMax(Node root, int axis) {
if (root == null) {
return null;
}
if (root.getAxis() == axis) {
if (root.right == null) {
return root;
}
return findMax(root.right, axis);
} else {
Node left = findMax(root.left, axis);
Node right = findMax(root.right, axis);
Node[] candidates = {left, root, right};
return Arrays.stream(candidates).filter(Objects::nonNull).max(Comparator.comparingInt(a -> a.point.getCoordinate(axis))).orElse(null);
}
}
/**
* Delete the node with the given point.
*
* @param point the point to delete
* */
public void delete(Point point) {
Node node = search(point).orElseThrow(() -> new IllegalArgumentException("Point not found"));
root = delete(root, node);
}
/**
* Delete the specified node from a subtree.
*
* @param root The root of the subtree to delete from
* @param node The node to delete
*
* @return The new root of the subtree
*/
private Node delete(Node root, Node node) {
if (root == null) {
return null;
}
if (root.equals(node)) {
if (root.right != null) {
Node min = findMin(root.right, root.getAxis());
root.point = min.point;
root.right = delete(root.right, min);
} else if (root.left != null) {
Node min = findMin(root.left, root.getAxis());
root.point = min.point;
root.left = delete(root.left, min);
} else {
return null;
}
}
if (root.getAxisCoordinate() < node.point.getCoordinate(root.getAxis())) {
root.left = delete(root.left, node);
} else {
root.right = delete(root.right, node);
}
return root;
}
/**
* Finds the nearest point in the tree to the given point.
*
* @param point The point to find the nearest neighbor to.
* */
public Point findNearest(Point point) {
return findNearest(root, point, root).point;
}
/**
* Finds the nearest point in a subtree to the given point.
*
* @param root The root of the subtree to search in.
* @param point The point to find the nearest neighbor to.
* @param nearest The nearest neighbor found so far.
* */
private Node findNearest(Node root, Point point, Node nearest) {
if (root == null) {
return nearest;
}
if (root.point.equals(point)) {
return root;
}
int distance = Point.comparableDistance(root.point, point);
int distanceExceptAxis = Point.comparableDistanceExceptAxis(root.point, point, root.getAxis());
if (distance < Point.comparableDistance(nearest.point, point)) {
nearest = root;
}
nearest = findNearest(root.getNearChild(point), point, nearest);
if (distanceExceptAxis < Point.comparableDistance(nearest.point, point)) {
nearest = findNearest(root.getFarChild(point), point, nearest);
}
return nearest;
}
}