private int count(Node<T> node) { if (node == null) { return 0; } int leftTreeSize = count(node.left); if (leftTreeSize == Integer.MIN_VALUE) { return Integer.MIN_VALUE; } if (node.count != leftTreeSize) { return Integer.MIN_VALUE; } int rightTreeSize = count(node.right); if (rightTreeSize == Integer.MIN_VALUE) { return Integer.MIN_VALUE; } return leftTreeSize + 1 + rightTreeSize; 请为以上代码编写测试类 }
时间: 2024-02-07 18:03:10 浏览: 53
好的,以下是一个可能的测试类,可以用于测试上面的代码:
```
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
public class NodeCountTest {
private Node<Integer> root;
@Before
public void setUp() throws Exception {
// 构造一棵符合要求的二叉树
root = new Node<>(3);
root.left = new Node<>(1);
root.left.left = new Node<>(0);
root.left.right = new Node<>(2);
root.right = new Node<>(5);
root.right.left = new Node<>(4);
root.right.right = new Node<>(6);
}
@Test
public void testCount() {
int result = count(root);
assertEquals(7, result);
}
private int count(Node<Integer> node) {
if (node == null) {
return 0;
}
int leftTreeSize = count(node.left);
if (leftTreeSize == Integer.MIN_VALUE) {
return Integer.MIN_VALUE;
}
if (node.count != leftTreeSize) {
return Integer.MIN_VALUE;
}
int rightTreeSize = count(node.right);
if (rightTreeSize == Integer.MIN_VALUE) {
return Integer.MIN_VALUE;
}
return leftTreeSize + 1 + rightTreeSize;
}
}
```
这个测试类中,我们首先构造了一棵符合要求的二叉树,然后使用 `count()` 方法计算这棵二叉树的节点数目,最后使用 JUnit 的断言方法 `assertEquals()` 来判断计算结果是否正确。如果测试通过,那么说明上面的代码实现是正确的。
阅读全文