Java 通过ObjectInputStream创建的BinaryTree的NullPointerException
我正在使用ObjectInputStream从保存在二进制文件中的数据(而不是节点)构建一个二叉树。但是,当控件返回到驱动程序时,作为结果创建的树对象似乎为null,我看到了NullPointerException。调用Java 通过ObjectInputStream创建的BinaryTree的NullPointerException,java,nullpointerexception,objectinputstream,Java,Nullpointerexception,Objectinputstream,我正在使用ObjectInputStream从保存在二进制文件中的数据(而不是节点)构建一个二叉树。但是,当控件返回到驱动程序时,作为结果创建的树对象似乎为null,我看到了NullPointerException。调用testTree中的第一个方法getHeight()。当我尝试遍历新构建的树对象时,它返回空白。我不明白为什么。有什么建议吗 以下是我试图简要介绍的相关代码: public static void main(String [] args) { .... BST<Intege
testTree
中的第一个方法getHeight()。当我尝试遍历新构建的树对象时,它返回空白。我不明白为什么。有什么建议吗
以下是我试图简要介绍的相关代码:
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;
}
}
publicstaticvoidmain(字符串[]args)
{
....
BST T=新的BST();
T.buildTree(“BST.dat”);
测试树(T);
...
}
公共类BST我的看法是,您试图从子类访问父函数,但由于未初始化,父函数在其中使用的值可能为null。这有很多种可能性,但这只是其中一种显而易见的可能性,因为它涉及到继承。干杯 如果(node!=null)
条件,则使用的重新读取树的可能重复项。它仍然导致nullPointerException。