[英]Binary tree of strings giving me errors Java
我有一個二叉樹,它保留變量和它們從.txt文件中出現的行。 之前,我曾在方法中錯誤地創建了新節點,以檢查其是否包含,從而創建了大量節點。 那時它打印了正確的信息,但是退出並出現錯誤。 我意識到了這一點,並將其移至insert方法,但現在print僅給出一個錯誤,但沒有結果。 我已經為此苦苦掙扎了一段時間了,我不知道這是怎么回事。 任何幫助將不勝感激。
我對這兩種方法的代碼是:
public void insert(String inputVar, int line, BinaryNode t)
{
if (t.var == null)
{
t.var = inputVar;
t.lines[t.count] = line;
t.count++;
}
else if (inputVar.compareTo(t.var) < 0)
{
if (t.left == null)
t.left = new BinaryNode(100);
insert(inputVar, line, t.left);
}
else if (inputVar.compareTo(t.var) > 0)
{
if (t.right == null)
t.right = new BinaryNode(100);
insert(inputVar, line, t.right);
}
}
public void printTree(BinaryNode t)
{
if (t.var == null)
{
}
else if (t.left == null && t.right !=null)
{
System.out.printf("The variable %s appears at lines ", t.var);
for (int l = 0; l < t.count; l++)
{
System.out.printf("%d ", t.lines[l]);
}
System.out.println();
printTree(t.right);
}
else if (t.right == null && t.left != null)
{
printTree(t.left);
System.out.printf("The variable %s appears at lines ", t.var);
for (int l = 0; l < t.count; l++)
{
System.out.printf("%d ", t.lines[l]);
}
System.out.println();
}
else
{
printTree(t.left);
System.out.printf("The variable %s appears at lines ", t.var);
for (int l = 0; l < t.count; l++)
{
System.out.printf("%d ", t.lines[l]);
}
System.out.println();
printTree(t.right);
}
}
我從printTree中的if語句中得到一個錯誤。
當兩個t.right == null && t.left == null
時,您可能會遇到最后一種情況( else
在printTree()中),因此您對兩個(空)孩子都進行了遞歸調用,然后在第一次檢查時落入NPE
if(t.var == null)
其中t
為空
您的基本情況是t == null
,但是您的代碼無法處理這種情況。 也就是說,空樹不是沒有變量的節點,而是空節點。
為什么您的打印方法必須如此復雜?
public void printTree( BinaryNode t ) {
if ( null == t )
return;
printTree( t.left );
System.out.printf( "The variable %s appears at lines ", t.var );
for ( int l = 0; l < t.count; l++ )
System.out.printf( "%d ", t.lines[ l ] );
System.out.println();
printTree( t.right );
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.