0
我遇到問題。我做了以下程序,因爲我想創建一個二叉樹節點,讓實例化器創建一堆樹節點,然後讓計數器計算節點和樹葉。我的問題是這樣的:當我調用BTNode(null,null,null)時,我總是收到一個空指針異常。進一步說:我必須爲這些值放入null,根據定義節點指向其他節點,並且當您實例化根時,沒有其他節點可供左右指向,因此它必須爲空。出於某種原因,這完全是用java來完成的,它會拋出一個空指針異常。爲什麼:我沒有線索,我甚至在聲明新的BTNode並將它們分配爲左側和右側之前從未引用這些值。而且,它甚至不會超過構造函數!實例化二叉樹中的根的問題
請幫忙!
public class binarytree {
static int nodeCounter=0;
static int leafCounter=0;
public static class BTNode{
char c;
BTNode left;
BTNode right;
public BTNode(Character d, BTNode left1, BTNode right1){
c=d;left=left1;right=right1;}
}
public static void Instantiator(BTNode root){
int counter=10;
Instantiator1(root,counter);
}
public static void Instantiator1(BTNode root,int counter){
if (counter<=0){
return;}
BTNode a=new BTNode(null,null,null);
BTNode b=new BTNode(null,null,null);
root.left=a;
root.right=b;
counter--;
Instantiator1(a,counter);
Instantiator1(b,counter);
}
public static int Testleaf(BTNode n){
if(n.left==null && n.right==null)
return 1;
else return 0;
}
public static int Testnode(BTNode n){
if(!(n.left==null && n.right==null))
return 1;
else return 0;
}
public static void printNodesandLeaves(BTNode root){
counter(root);
System.out.println("Nodes are"+nodeCounter);
System.out.println("leaves are"+leafCounter);
}
public static void counter(BTNode r){
nodeCounter+=Testnode(r);
leafCounter+=Testleaf(r);
if (!(r.left==null))
counter(r.left);
if (!(r.right==null))
counter(r.right);}
public static void main(String[] args){
BTNode root=new BTNode(null,null,null);
Instantiator(root);
printNodesandLeaves(root);
}}
它永遠不會讓我印象深刻,這裏的一些傢伙有多聰明。謝謝,那有效。 – QuestionAsker