'binary search tree 2D, java, X and Y value nodes
i'm trying to have a binary search tree with two values per node, an x and a y, all I'm trying to do is have it insert by shifting values and don't know how to get started
public class Node {
//instance variable of Node class
public double x;
public double y;
public Node left;
public Node right;
//constructor
public Node(Point p) {
this.x = p.getX();
this.y = p.getY();
this.left = null;
this.right = null;
}
}
that's how i got the Node set up and to insert I'm trying to use recurstion
// insert method to insert the new Date
public void insert(Point p) {
insert(root, p);
}
public Node insert(Node current, Point p) {
// Base Case: root is null or not
if (root == null) {
// Insert the new data, if root is null.
root = new Node(p);
return root;
}
Node parent = current;
if (p.getY() <= parent.y) {
if(current.left == null) {
current.left(p);
return current;
}
else {
insert(current.left, p);
}
}
if (p.getY() > parent.y) {
if(current.right == null) {
current.right(p);
return current;
}
else {
insert(current.right, p);
}
}
return current;
}
and to test the code i just have a simple insert statement
bst.insert(new Point(10,10));
bst.insert(new Point(100, 5));
bst.insert(new Point(100, 20));
bst.insert(new Point(50, 3));
bst.insert(new Point(110, 7));
and I'm having trouble with two things, i can't seem to get the binary search tree to evaluate using the Y value, so for example the (10,10) is (x,y) and is the root, the (100,5) has a lower Y value so should be left but for somereason it's throwing all my code into the root and then how can i use the Y value for the root, and then use the X value for comparison at level 1 and keep changing from X to Y
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
