MCPcopy Create free account
hub / github.com/MolinDeng/Princeton-algs4 / KdTree

Class KdTree

05Lab-Kd Tree/KdTree.java:15–191  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

13import java.util.ArrayList;
14
15public class KdTree {
16 private Node root;
17 private int n;
18
19 // construct an empty set of points
20 public KdTree() {
21 root = null;
22 n = 0;
23 }
24
25 // is the set empty?
26 public boolean isEmpty() {
27 return root == null;
28 }
29
30 // number of points in the set
31 public int size() {
32 return n;
33 }
34
35 // add the point to the set (if it is not already in the set)
36 public void insert(Point2D p) {
37 if (p == null) throw new IllegalArgumentException();
38 if (contains(p)) return;
39 root = put(root, p, true, 0, 0, 1, 1);
40 n++;
41 }
42
43 private Node put(Node x, Point2D p, boolean isXPartition, double xmin, double ymin, double xmax,
44 double ymax) {
45 if (x == null) return new Node(p, new RectHV(xmin, ymin, xmax, ymax));
46 int cmp = isXPartition ? Double.compare(p.x(), x.p.x())
47 : Double.compare(p.y(), x.p.y());
48
49 if (cmp < 0) {
50 if (isXPartition) xmax = x.p.x();
51 else ymax = x.p.y();
52 x.left = put(x.left, p, !isXPartition, xmin, ymin, xmax, ymax);
53 }
54 else {
55 if (isXPartition) xmin = x.p.x();
56 else ymin = x.p.y();
57 x.right = put(x.right, p, !isXPartition, xmin, ymin, xmax, ymax);
58 }
59 return x;
60 }
61
62 // does the set contain point p?
63 public boolean contains(Point2D p) {
64 if (p == null) throw new IllegalArgumentException();
65 return get(root, p, true) != null;
66 }
67
68 private Point2D get(Node x, Point2D p, boolean isXPartition) {
69 if (p == null) throw new IllegalArgumentException();
70 if (x == null) return null;
71 if (p.compareTo(x.p) == 0) return x.p;
72 int cmp = isXPartition ? Double.compare(p.x(), x.p.x())

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected