I am building a binary tree from data (not nodes) saved in a binary file using the ObjectInputStream. However, it seems when the control is returned to the driver program, the tree Object created as a result is null and I see the NullPointerException. The exception occurs when the first method getHeight()
in testTree
is called. And when I try to iterate through the newly built tree object, it returns blank. I don't understand why. Any suggestions?
Here is the relevant code that I tried to keep brief:
public static void main(String [] args)
{
....
BST<Integer> T = new BST<Integer>();
T.buildTree("BST.dat");
testTree(T);
...
}
public class BST<T extends Comparable<? super T>>
extends CBT<T>
implements STInterface<T>
{
private BN<T> root;
public BST()
{
super();
}
//other methods here.
}
public class CBT<T extends Comparable<? super T>> extends BT<T> implements CTInterface<T>
{
public ComparableBinaryTree()
{
super();
}
}
public class BT<T> implements BTInterface<T>
{
private BN<T> root;
public int getHeight()
{
return root.getHeight();
}
...
public void buildTree(String fileName)
{
try
{
ObjectInputStream IS = new ObjectInputStream(
new FileInputStream(fileName));
double numberOfNodes = (double)IS.readInt();
BN<T> root = new BN<>();
RecReadTree(IS, numberOfNodes, root);
IS.close();
}
catch (IOException e)
{
System.out.println("Reading problem");
}
}
....
}
private void RecReadTree(ObjectInputStream IS, double numberOfNodes, BN<T> node)
{
if (node != null)
{
try
{
if (numberOfNodes == 1)
{
@SuppressWarnings("unchecked")
T data = (T) IS.readObject();
node.setData(data);
return;
}
double left = Math.ceil((numberOfNodes - 1)/2.0); //ceiling
double right = Math.floor((numberOfNodes - 1)/2.0); //floor
BN<T> leftChild = new BN<>();
node.setLeftChild(leftChild);
RecReadTree(IS, left, leftChild);
@SuppressWarnings("unchecked")
T data = (T) IS.readUnshared();
node.setData(data);
if (right > 0)
{
//new node
BN<T> rightChild = new BN<>();
node.setRightChild(rightChild);
RecReadTree(IS, right, rightChild);
}
}
catch (Exception e)
{
System.out.println("Rec Reading Problem" + e);
}
}
}
}
}
public class BN<T>
{
public int getHeight()
{
return getHeight(this);
} // end getHeight
private int getHeight(BN<T> node)
{
int height = 0;
if (node != null)
height = 1 + Math.max(getHeight(node.getLeftChild()),
getHeight(node.getRightChild()));
return height;
}
}
EDIT: I have added the not null condition when building the binary tree. It still causes an error. It seems to be something to do with the scope and inheritance because I can access the getHeight()
method no problem from inside RecReadTree
, if I needed to.