二叉树测试?

时间:2016-02-22 18:09:08

标签: java tree binary-tree

我有一个BinaryTree类,一个TreeNode类和一个BinaryTestClass,它创建一个BinaryTree,其中值可以作为root插入TreeNode。但是,当我在测试类上运行程序时,它并没有显示应该显示的所有内容。

BinaryTree类:

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对象的方法。但是,当我运行测试方法时,它只出现在&#34;插入值:&#34;部分代码。

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);
      } 
  }

我该怎么做,以便显示放在树中的完整值列表?

3 个答案:

答案 0 :(得分:0)

简单地执行System.out.println(tree)将不会打印出树中的值。您需要在printTree()类中创建一个方法,例如BinaryTree,它将遍历您的树并打印数字。

答案 1 :(得分:0)

你不能只说System.out.println(树),你必须编写一个自定义方法。我已经起草了一个你可以参考的基本方法。这可能不完全正确。

public static void printTree(Treenode root)
{
if(root == null)
return;
else
    {
        System.out.println(root.value);
        printTree(root.left());
        printTree(root.right());
     }
}

这是预订。你可以写后序或订购

答案 2 :(得分:0)

如果要打印类,必须覆盖Object的toString()方法。

相关问题