views:

52

answers:

1

Hi Im having some trouble when inserting to the right of a node in a binary tree... I just dont see why the exception is happening. This is the method to inset:

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

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

This is the code in my main class

public class Testing {

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

}

}

I'm only able to insert, 30, 12, and 16. Not sure what's going on.... This is the error I get, it happens in the attachRight method

Exception in thread "main" proj5.TreeViolationException at proj5.BinaryTree.attachRight(BinaryTree.java:98)

TreeViolationException is just a class that I have that extends RuntimeException

+1  A: 

From the information given, the exception should come from this line:

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

because root.right.attachRight() has already been called on this line:

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

and root.right already has right node. Why it comes earlier, is impossible to diagnose right now. You should provide more information (e.g. BinaryTree class full implementation).

martsraits
I think//insert 1 -> right(12)root.right.attachRight(new BinaryTree<Integer>());should be//insert 1 -> right(12)root.left.attachRight(new BinaryTree<Integer>());
Skip Head