我正在尝试用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;
}
答案 0 :(得分:0)
在isPresent
方法中,您忽略了在isPresent
和left
子项上调用right
的结果。根据需要将left
或right
子项分配给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;
}