private static void draw(KdNode tree, boolean vertical) {
    if (tree == null) return;
    tree.p.draw();

    if (vertical) {
      StdDraw.setPenColor(255, 0, 0);
      StdDraw.line(0, tree.p.y(), 1, tree.p.y());
    } else {
      StdDraw.setPenColor(0, 0, 255);
      StdDraw.line(tree.p.x(), 0, tree.p.x(), 1);
    }
    draw(tree.l, !vertical);
    draw(tree.r, !vertical);
  }
 public void draw() { // draw all of the points to standard draw
   draw(root, true);
 }
Example #3
0
  public static void main(String[] args) {

    In in = new In("/Users/eugene/Downloads/kdtree/horizontal8.txt");

    StdDraw.show(0);

    // initialize the data structures with N points from standard input
    // eugeneto.princeton.algorithm.exercises.week5.PointSET brute = new
    // eugeneto.princeton.algorithm.exercises.week5.PointSET();
    KdTree kdtree = new KdTree();
    while (!in.isEmpty()) {
      double x = in.readDouble();
      double y = in.readDouble();
      Point2D p = new Point2D(x, y);
      kdtree.insert(p);
      // brute.insert(p);
    }

    double x0 = 0.0, y0 = 0.0; // initial endpoint of rectangle
    double x1 = 0.0, y1 = 0.0; // current location of mouse
    boolean isDragging = false; // is the user dragging a rectangle

    // draw the points
    StdDraw.clear();
    StdDraw.setPenColor(StdDraw.BLACK);
    StdDraw.setPenRadius(.01);
    kdtree.draw();

    while (true) {
      StdDraw.show(40);

      // user starts to drag a rectangle
      if (StdDraw.mousePressed() && !isDragging) {
        x0 = StdDraw.mouseX();
        y0 = StdDraw.mouseY();
        isDragging = true;
        continue;
      }

      // user is dragging a rectangle
      else if (StdDraw.mousePressed() && isDragging) {
        x1 = StdDraw.mouseX();
        y1 = StdDraw.mouseY();
        continue;
      }

      // mouse no longer pressed
      else if (!StdDraw.mousePressed() && isDragging) {
        isDragging = false;
      }

      RectHV rect =
          new RectHV(Math.min(x0, x1), Math.min(y0, y1), Math.max(x0, x1), Math.max(y0, y1));
      // draw the points
      StdDraw.clear();
      StdDraw.setPenColor(StdDraw.BLACK);
      StdDraw.setPenRadius(.01);
      kdtree.draw();

      // draw the rectangle
      StdDraw.setPenColor(StdDraw.BLACK);
      StdDraw.setPenRadius();
      rect.draw();

      // draw the range search results for brute-force data structure in red
      StdDraw.setPenRadius(.03);
      StdDraw.setPenColor(StdDraw.RED);
      for (Point2D p : kdtree.range(rect)) p.draw();

      // draw the range search results for kd-tree in blue
      StdDraw.setPenRadius(.02);
      StdDraw.setPenColor(StdDraw.BLUE);
      for (Point2D p : kdtree.range(rect)) p.draw();

      StdDraw.show(40);
    }
  }