【发布时间】:2016-02-23 02:46:06
【问题描述】:
我有一个 BinaryTree 类、一个 TreeNode 类和一个 BinaryTestClass,它们创建了一个 BinaryTree,其中值可以作为根插入到 TreeNode 中。但是,当我在测试类上运行程序时,它并没有显示应该显示的所有内容。
二叉树类:
public class BinaryTree <T extends Comparable<T>> implements BTree<T>{
TreeNode<T> root;
public BinaryTree(){
root = null;
}
public BTree<T> left() {
// TODO Auto-generated method stub
return left();
}
public BTree<T> right() {
// TODO Auto-generated method stub
return right();
}
public void insert(T value) {
if (root == null){
root = new TreeNode(value);
}else if (value.compareTo(value()) < 0){
root.left().insert(value);
} else{
root.right().insert(value);
}
}
public T value() {
return value();
}
}
TreeNode 类:
public class TreeNode<T extends Comparable<T>>{
T value;
BinaryTree<T> left, right;
public TreeNode(T value) {
this.value = value;
left = new BinaryTree<T>();
right = new BinaryTree<T>();
}
public T value() {
return value;
}
public BinaryTree<T> left() {
return left;
}
public BinaryTree<T> right() {
return right;
}
}
在这个测试类中,我有实例化一个空 BinaryTree 对象的方法。但是,当我运行测试方法时,它只出现在“插入值:”部分代码中。
public class BinaryTreeTest {
/**
* @throws java.lang.Exception
*/
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
/**
* @throws java.lang.Exception
*/
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {
}
/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception {
}
@Test
public void test() {
BinaryTree tree = new BinaryTree(); // empty tree
int intVal;
// insert 10 random ints
System.out.print("Inserting the values: ");
for (int i = 1; i <= 10; i++) {
intVal = (int) (Math.random()*100);
System.out.print(intVal + " ");
tree.insert(intVal);
}
System.out.println(tree);
}
}
我该怎么做才能显示放入树中的完整值列表?
【问题讨论】:
标签: java tree binary-tree