关于重构递归2dtree包含方法的建议

时间:2015-07-24 14:44:48

标签: java recursion

我正在参加Coursera算法课程(顺便说一句,这很棒)我正在为其中一个作业实施2DTree。此树将点插入树中但与BST不同,因为它交替比较x值和y值以决定将点放在树中的位置。无论如何,我想要批评我的contains方法。它工作正常,但我相信我的知识存在差距,使我无法简化它。具体来说,我必须传递一个名为 found 的布尔值。有没有办法在我的代码中不必这样做?请批评你认为可能有助于我的学习和发展的任何事情。以下是相关代码

private enum Orientations {
    compareX, compareY,
}

public boolean contains(Point2D p) {
    checkForNullArgument(p);
    return contains(root, p, Orientations.compareX,false);
}            // does the set contain point p?

private boolean contains(Node node, Point2D point, Orientations orientation,boolean found) {
    if(node == null)
        return false;
    if (node.p.equals(point)) {
        StdOut.println("Found equal point");
        found = true;
        return found;
    }
    switch (orientation) {
        case compareX:
            Comparator<Point2D> cmpX = Point2D.X_ORDER;
            int compX = cmpX.compare(point, node.p);
            if (compX < 0) found = contains(node.left, point, Orientations.compareY,found);
            else if (compX >= 0) found = contains(node.right, point, Orientations.compareY,found);
            break;
        case compareY:
            Comparator<Point2D> cmpY = Point2D.Y_ORDER;
            int compY = cmpY.compare(point, node.p);
            if (compY < 0) found = contains(node.left, point, Orientations.compareX,found);
            else if (compY >= 0) found = contains(node.right, point, Orientations.compareX,found);
            break;
    }
    return found;
} 

1 个答案:

答案 0 :(得分:0)

您当然不需要找到参数。摆脱它,只需在开关之前将其添加到您的函数中:

private boolean contains(Node node, Point2D point, Orientations orientation) {
  ...
  boolean found=false;
  ...