在@hyde 告诉我之后,这就是我所做的:
Node<E> current = root;
int count = 0;
public int getNumberOfInteriorNodes() {
if (current == null || (current.left == null && current.right == null)) {
return count;
}
else {
if (current.right != null) {
Node<E> tmp = current;
current = current.right;
count += getNumberOfInteriorNodes();
current = tmp;
}
if (current.left != null) {
Node<E> tmp = current;
current = current.left;
count += getNumberOfInteriorNodes();
current = tmp;
}
return count + 1;
}
}
下面是我的测试方法的样子:
public static void testGetNumberOfInteriorNodes() {
BinarySearchTree<Integer> t;
t = new BinarySearchTree<Integer>();
Assert.assertEquals(0, t.getNumberOfInteriorNodes());
t.add(2);
Assert.assertEquals(0, t.getNumberOfInteriorNodes());
t.add(1);
Assert.assertEquals(1, t.getNumberOfInteriorNodes());
t.add(5);
Assert.assertEquals(1, t.getNumberOfInteriorNodes());
t.add(4);
Assert.assertEquals(2, t.getNumberOfInteriorNodes());
t.add(3);
Assert.assertEquals(3, t.getNumberOfInteriorNodes());
t.add(6);
Assert.assertEquals(3, t.getNumberOfInteriorNodes());
}
我的测试在第 3 个断言中失败并出现错误。计数永远不会超过零。这是我得到的错误:
Failure: junit.framework.AssertionFailedError: expected:<1> but was:<0>
任何进一步的帮助将不胜感激。