Question

We have an assignment in my data structures class where we have to manually build a binary tree with 7 nodes total, and display the data in each node in a preorder traversal. The root node has 2 children, and each of those 2 children has 2 children. I've got up to the point of creating the whole left side down to the end of the first tree, but am stuck at this point with a Null Pointer Exception once I create the first Right Child. I've searched other projects similar to this and I still can't seem to find out what the problem with this code is. I've found code that creates the tree's much better than we've been assigned to do, but we are limited in class to manually creating the left and right children. Any outside perspective to help out what is probably a simple program to create would be greatly appreciated!

public class Main {

public static void main(String[] args) {

    Node a = new Node(1);
    Node b = new Node(2);
    Node c = new Node(3);
    Node d = new Node(4);
    Node e = new Node(5);
    Node f = new Node(6);
    Node g = new Node(7);
    BinaryTree t = new BinaryTree(a);

    t.addleft(a);
    t.addleft(b);
    t.addleft(c);
    t.addParent();
    t.addRight(d);
    t.addParent();
    //t.addParent();
    //t.addRight(e);
    //t.addleft(f);
    //t.addParent();
    //t.addRight(g);


    //System.out.println(n.getData());          

    t.preOrder(t.root);
}

}

public class BinaryTree {
Node root;
Node current;

public BinaryTree(Node n){
    root = n;
    n.setParent(current);
    current = n;
}

public void addleft(Node n){    
    current.setLeft(n);
    current = n;        
}

public void addRight(Node n){   
    current.setRight(n);
    current = n;        
}

public void addParent(){
    current = current.getParent();
}

public void preOrder(Node n){
    if(n != null){
        System.out.println(n.getData());
        preOrder(n.leftChild);
        preOrder(n.rightChild);
        return;
    }
    return;

}

}

public class Node {
Node parent;
Node rightChild;
Node leftChild;
int data;

public Node(int i) {
    data = i;
    parent = null;
    rightChild = null;
    leftChild = null;
}

public int getData() {
    return data;
}

public Node getParent() {
    return parent;
}

public void setParent(Node aParent) {
    parent = aParent;
}

public Node getLeft() {
    return leftChild;
}

public void setLeft(Node left) {
    leftChild = left;
}

public void setRight(Node right) {
    rightChild = right;
}

public Node getRight() {
    return rightChild;
}
}
Was it helpful?

Solution

Its because when you create the Binary Tree with Node a as your root, c does not have a parent.

When you call

t.addParent();
t.addRight(d);

the first line sets current to null, then the second line attempts to use the null value.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top