return语句没有将控制权返回给java中的调用者

时间:2014-12-05 22:51:54

标签: java return binary-tree binary-search-tree

我正在尝试用Java练习二进制树,并尝试编写一个" isPresent"功能。但是如果参数(testInt)不是根节点值,则该函数不起作用。它正在进入无限循环。我确实错过了一些愚蠢的事情。

public class Node {
    // Attributes
    int value;
    Node leftChild;
    Node rightChild;

    // Constructor
    Node (int value) {
        this.value = value;
    }

    // Getter
    int getValue() {
        return value;
    }

    boolean isPresent(int testInt) {
        Node presentNode = this;
        while (presentNode != null) {
            if (presentNode.getValue() == testInt) {
                return true;
            } else if (testInt < presentNode.getValue()) {
                presentNode.leftChild.isPresent(testInt);
            } else {
                presentNode.rightChild.isPresent(testInt);
            }
        }
        return false;
    }
}

public static void main(String args[]) {
    int[] integers = new int[size];
    Arrays.sort(integers);
    Node binarySearchTree = createBSTFromSortedArray(integers, 0, size - 1);
    if (binarySearchTree.isPresent(testInt)) {
        System.out.println("Yes");
    } else {
        System.out.println("No");
    }
    in.close();
}

private static Node createBSTFromSortedArray(int[] integers, int start, int end) {
    if (end < start) {
        return null;
    }
    int mid = (start + end) / 2;
    Node binarySearchTree = new Node(integers[mid]);
    binarySearchTree.leftChild = createBSTFromSortedArray(integers, start, mid - 1);
    binarySearchTree.rightChild = createBSTFromSortedArray(integers, mid + 1, end);
    return binarySearchTree;
}

1 个答案:

答案 0 :(得分:0)

isPresent方法中,您忽略了在isPresentleft子项上调用right的结果。根据需要将leftright子项分配给presentNode

更改

} else if (testInt < presentNode.getValue()) {
     presentNode.leftChild.isPresent(testInt);
} else {
     presentNode.rightChild.isPresent(testInt);
}

} else if (testInt < presentNode.getValue()) {
    presentNode = presentNode.leftChild;
} else {
    presentNode = presentNode.rightChild;
}