[英]Java - loading a binary tree from a text file
我正在嘗試從相應的字符串文件加載二叉樹。 我很早就在代碼中得到了NoSuchElementException錯誤(確切的行被注釋),我不確定該算法是否可以開始工作。 文本文件的排序如下:
hello 0 0
my 0 0
name 1 1
其中第一個數字表示節點是否有左子節點,第二個數字表示節點是否有正確的子節點。
我的BinaryTree類有兩個子類,ConsTree和EmptyTree,每個樹都有自己的左右子樹。
以下是該方法的代碼:
BinaryTree<String> loadFile(String filename)
{
File file = new File(filename);
Scanner scanny = new Scanner(file);
Stack<BinaryTree<String>> stack = new Stack<BinaryTree<String>>();
while(scanny.hasNextLine())
{
String data = scanny.next();
int leftChild = scanny.nextInt();
int rightChild = scanny.nextInt();
ConsTree<String> tree = new ConsTree<String>(data, null, null);
if(rightChild == 1) //this line throws a NoSuchElementException
{
tree.right = stack.pop();
}
if(leftChild == 1)
{
tree.left = stack.pop();
}
stack.push(tree);
}
return stack.pop();
}
以下是我的ConsTree類的構造函數。 這是我制作方法時唯一的其他代碼。
public ConsTree(T data, BinaryTree<T> left, BinaryTree<T> right)
{
this.data = data;
this.left = left;
this.right = right;
}
public ConsTree(T data)
{
this.left = new EmptyTree();
this.right = new EmptyTree();
this.data = data;
}
EmptyTree類的構造函數是完全空白的。
這是我用來測試方法的內容:
public static void main(String[] args)
{
Loader l = new Loader(); //the class with the load method in it
BinaryTree<String> t = l.loadFile(args[0]);
System.out.println(t);
}
args [0]包含文本文件的名稱,該文件具有在問題開頭列出的內容。
如果有人能把我放在正確的方向,那將會有所幫助。
如果您需要任何其他信息,請告訴我。
你對於代碼來讀取數據元素if
條件似乎是罰款。 if(rightChild == 1)
,此行不會出現錯誤 。 請仔細看,它必須來自這一行tree.right = stack.pop();
或包含堆棧操作的其他行。
我懷疑它來自tree.right
因為沒有這樣的元素。 如果您可以共享其余代碼,那么找到確切的問題會很有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.