TreeViolationException

TreeViolationException

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

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方法中

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

TreeViolationException只是我扩展RuntimeException的一个类

最佳答案

根据给出的信息,异常应来自以下行:

//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类的完整实现)。

10-08 17:17