这是我的 getBefore 方法
public Node getBefore() {
return getBeforeHelper(root, this.data);
}
public Node getBeforeHelper(Node node, K key) {
Node current = null;
if(node != null) {
if(node.data == key) {
if(node.left != null) {
current = node.left;
while(current.right != null) {
current = current.right;
}
System.out.println(current.get());
return current;
}
}
else if(lessThan.test(key, node.data)) {
return getBeforeHelper(node.left, key);
}
else if(lessThan.test(node.data, key)) {
return getBeforeHelper(node.right, key);
}
}
else {
return null;
}
return current;
}
这是它未能通过的 Junit 测试
@Test
public void beforeBST() {
BinarySearchTree<Integer> bst = new BinarySearchTree<>((Integer x, Integer y) -> x < y);
assertTrue(bst.isEmpty());
int[] a = new int[] { 12, 4, 18, 5, 11, 8, 15, 9, 17, 20, 3, 13, 19, 2, 14, 7, 6, 10, 1, 16 };
int n = a.length;
for (Integer key : a)
bst.insert(key);
assertNull(bst.search(1).getBefore());
for (int i = 2; i <= n; i++) {
System.out.println(bst.search(2).getBefore());
assertTrue(i - 1 == bst.search(i).getBefore().get());
}
}
它在最后一个 for 循环中到达 assertTrue,然后因空指针异常而失败。为什么会抛出空指针?
慕娘9325324
叮当猫咪
相关分类