public boolean insert(Point2D p) { if (p.equals(value)) { return false; } if (onLeft(p)) { if (left == null) { final TreeNode treeNode = newNode(p, this); treeNode.rect = even ? new RectHV(rect.xmin(), rect.ymin(), value.x(), rect.ymax()) : new RectHV(rect.xmin(), rect.ymin(), rect.xmax(), value.y()); left = treeNode; return true; } else { return left.insert(p); } } else if (onRight(p)) { if (right == null) { TreeNode treeNode = newNode(p, this); treeNode.rect = even ? new RectHV(rect.xmin(), value.y(), rect.xmax(), rect.ymax()) : new RectHV(rect.xmin(), value.y(), rect.xmax(), rect.ymax()); right = treeNode; return true; } else { return right.insert(p); } } return false; }
public boolean contains(Point2D p) { if (p.equals(value)) { return true; } else if (onLeft(p)) { return left != null && left.contains(p); } else if (onRight(p)) { return right != null && right.contains(p); } else { System.out.println("Impossible!"); return false; } }
public Point2D ceiling(Point2D p, boolean inclusive) { requireNonNull(p); if (value.equals(p)) { return value; } else if (onRight(p)) { if (right != null && right.onLeft(p)) { return inclusive ? value : right.value; } else if (right != null && right.onRight(p)) { return right.ceiling(p, inclusive); } else { return inclusive ? value : null; } } else if (onLeft(p)) { return left == null ? inclusive ? null : value : left.ceiling(p, inclusive); } else { return inclusive ? value : null; } }
private Node put(final Node x, final Point2D key, final boolean vertical) { if (x == null) { return new Node(key, 1); } double cmp; if (vertical) { cmp = key.x() - x.key.x(); } else { cmp = key.y() - x.key.y(); } if (key.equals(x.key)) { // do nothing } else if (cmp <= 0) { x.left = put(x.left, key, !vertical); x.N = 1 + size(x.left) + size(x.right); } else if (cmp > 0) { x.right = put(x.right, key, !vertical); x.N = 1 + size(x.left) + size(x.right); } return x; }