TreeViolationException问题

时间:2009-04-12 18:11:02

标签: java collections

我在插入二叉树中的节点右侧时遇到了一些问题...我只是不明白为什么会发生异常。这是插入的方法:

public void attachRight(BinaryTree<T> tree) {
    if (right != null) {
        throw new TreeViolationException();

    }
    if (tree != null) {
        tree.parent = this;
        right = tree;
    }
}

这是我主要课程中的代码

公共课测试{

public static void main(String[] args) {

    /*  the tree to be built                30
     *                                    /    \
     *                                  12     16
     *                                 /  \   /  \
     *                               null  1  2   5
     */

    //Create binary tree and set root to 30
    BinaryTree<Integer> root = new BinaryTree<Integer>();
    root.makeRoot(30);
    //System.out.println(root.getData()); //for verifying only

    //Insert 12 -> left(30)
    root.attachLeft(new BinaryTree<Integer>());
    root.left.setData(12);

    //Insert 16 -> right(30)
    root.attachRight(new BinaryTree<Integer>());
    root.right.setData(16);

    //insert 1 -> right(12)
    root.right.attachRight(new BinaryTree<Integer>());
    root.right.right.setData(1);

    //insert 2 -> left(16)
    root.right.attachLeft(new BinaryTree<Integer>());
    root.right.left.setData(2);

    //insert 5 -> right(16)
    root.right.attachRight(new BinaryTree<Integer>());
    root.right.right.setData(5);

    System.out.println(root.getData());
    System.out.println(root.left.getData());
    System.out.println(root.right.getData());

}

}

我只能插入,30,12和16.不确定发生了什么...... 这是我得到的错误,它发生在attachRight方法

线程“main”proj5.TreeViolationException中的异常     在proj5.BinaryTree.attachRight(BinaryTree.java:98)

TreeViolationException只是一个扩展RuntimeException

的类

1 个答案:

答案 0 :(得分:1)

根据给出的信息,例外应来自这一行:

//insert 5 -> right(16)
root.right.attachRight(new BinaryTree<Integer>());

因为root.right.attachRight()已在此行上调用:

//insert 1 -> right(12)
root.right.attachRight(new BinaryTree<Integer>());

和root.right已经有了正确的节点。为什么它更早出现,现在无法诊断。您应该提供更多信息(例如BinaryTree类完全实现)。