Beispiel #1
0
  public Point2D nearest(final Point2D p) {

    if (isEmpty()) {
      return null;
    }

    Holder<Point2D> nearest = new Holder<>(root.key);
    nearest(root, nearest, p, true);
    return nearest.value;
  }
Beispiel #2
0
  private void nearest(
      final Node node, final Holder<Point2D> nearest, final Point2D p, final boolean vertical) {

    if (node == null) {
      return;
    } else if (node.key.compareTo(p) == 0) {
      nearest.value = node.key;
      return;
    } else if (p.distanceTo(node.key) < p.distanceTo(nearest.value)) {
      nearest.value = node.key;
    }

    if (onTheLeft(p, node.key, vertical)) {
      nearest(node.left, nearest, p, !vertical);
      if (distanceToVertical(p, node.key, vertical) < p.distanceTo(nearest.value)) {
        nearest(node.right, nearest, p, !vertical);
      }
    } else if (onTheRight(p, node.key, vertical)) {
      nearest(node.right, nearest, p, !vertical);
      if (distanceToVertical(p, node.key, vertical) < p.distanceTo(nearest.value)) {
        nearest(node.left, nearest, p, !vertical);
      }
    }
  }