private KdNode put( KdNode nd, Point2D p, int turn, double xmin, double ymin, double xmax, double ymax) { if (nd == null) { sz++; return new KdNode(p, null, null, new RectHV(xmin, ymin, xmax, ymax)); } // Neglect nodes that collides with one // Already in the tree double ndx = nd.point.x(); double ndy = nd.point.y(); if (nd.point.equals(p)) return nd; else if (turn == 0) { if (p.x() < ndx) { nd.left = put(nd.left, p, 1 - turn, xmin, ymin, Math.min(ndx, xmax), ymax); } else { nd.right = put(nd.right, p, 1 - turn, Math.max(ndx, xmin), ymin, xmax, ymax); } } else { if (p.y() < ndy) { nd.left = put(nd.left, p, 1 - turn, xmin, ymin, xmax, Math.min(ndy, ymax)); } else { nd.right = put(nd.right, p, 1 - turn, xmin, Math.max(ndy, ymin), xmax, ymax); } } return nd; }
private void insertNoEmpty(KdNode tree, Point2D p, boolean vertical) { if (p.equals(tree.p)) return; double keyintree = vertical ? tree.p.y() : tree.p.x(); double keytocmp = vertical ? p.y() : p.x(); if (keytocmp < keyintree) { if (tree.l == null) { size++; tree.l = new KdNode(p); } else insertNoEmpty(tree.l, p, !vertical); } else { if (tree.r == null) { size++; tree.r = new KdNode(p); } else insertNoEmpty(tree.r, p, !vertical); } }