我想为四叉树实现插入方法。在这个四叉树中,我将插入某些形状,如矩形,三角形,圆形和菱形。所有shaoes都带有矩形边框(在此方法中,所有shaoes都被视为矩形)。我的方法适用于少数输入,但最重要的是我得到了提到的错误。
void insert(Node parent, GeometricObj shape) {
switch(parent.getType()) {
case EMPTY:
this.setShapeForNode(parent, shape);
break;
case LEAF:
if(needSplit(parent, shape)) {
this.setShapeForNode(parent, shape);
}
else {
this.split(parent);
this.insert(parent, shape);
for (int i = 0; i < parent.Shapes.size(); i++) {
this.insert(parent, parent.Shapes.get(i));
}
}
break;
case PARENT:
for (int i = 0; i < getQuadrantForShape(parent, shape.getX(), shape.getY(),
shape.getWidth(), shape.getHeight()).size(); i++) {
if(getQuadrantForShape(parent, shape.getX(), shape.getY(),
shape.getWidth(), shape.getHeight()).get(i).equals(parent.Quads.get(0))) {
this.insert(parent.Quads.get(0), shape);
}
if(getQuadrantForShape(parent, shape.getX(), shape.getY(),
shape.getWidth(), shape.getHeight()).get(i).equals(parent.Quads.get(1))) {
this.insert(parent.Quads.get(1), shape);
}
if(getQuadrantForShape(parent, shape.getX(), shape.getY(),
shape.getWidth(), shape.getHeight()).get(i).equals(parent.Quads.get(2))) {
this.insert(parent.Quads.get(2), shape);
}
if(getQuadrantForShape(parent, shape.getX(), shape.getY(),
shape.getWidth(), shape.getHeight()).get(i).equals(parent.Quads.get(3))) {
this.insert(parent.Quads.get(3), shape);
}
}
break;
}
}
拆分方法是:
void split(Node node) {
node.setType(NodeType.PARENT);
double x = node.getX();
double y = node.getY();
double halfwidth = node.getWidth()/ 2;
double halfheight = node.getHeight()/ 2;
node.setQuad1(new Node(x + halfwidth, y + halfheight, halfwidth, halfheight, node));
node.setQuad2(new Node(x, y + halfheight, halfwidth, halfheight, node));
node.setQuad3(new Node(x, y, halfwidth, halfheight, node));
node.setQuad4(new Node(x + halfwidth, y, halfwidth, halfheight, node));
node.Quads.add(node.quad1);
node.Quads.add(node.quad2);
node.Quads.add(node.quad3);
node.Quads.add(node.quad4);
}
GetQuadrantForShape方法返回新形状的象限列表。
void setShapeForNode(Node node, GeometricObj shape) {
if (node.getType() != NodeType.PARENT) {
node.setType(NodeType.LEAF);
node.Shapes.add(shape);
}
}
如果有人知道问题可能是什么,或者我做错了什么,或者我可以改进什么提示,请告诉我。如果你需要任何其他课程或方法,我会在这里附上。
更新:
boolean needSplit(Node node, GeometricObj shape) {
boolean result = false;
for (int i = 0; i < node.Shapes.size(); i++) {
GeometricObj o = node.Shapes.get(i);
result = this.overlaps(shape.getX(), shape.getY(), shape.getWidth(), shape.getHeight(), o);
if(result == false) {
break;
}
}
return result;
}
boolean overlaps (double x, double y, double width, double height, GeometricObj r) {
return x < r.getX() + r.getWidth() && x + width > r.getX() && y < r.getY() + r.getHeight() && y + height > r.getY();
}