I have a problem. I have made the following program because I wanted to create a binary tree node, have the instantiater create a bunch of tree nodes, and then have the counter count the nodes and the leaves. My problem is this: I keep getting a null pointer exception when I invoke BTNode(null,null,null). Further: I have to put null in for those values, the node by definition points to other nodes, and when you instantiate the root there's no other nodes for the right and left to point to, so it has to be null. This, for some reason, completely screws with java, and it throws a null pointer exception. Why: I have no clue, I never even reference those values before declaring new BTNodes and assigning them as left and right. Furthermore, it doesn't even get past the constructor!
Please help!
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开发者_如何学Go);
}
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);
}}
You are getting a NullPointerException
when auto-unboxing (Character) null
to a char
.
Your constructor
public BTNode(Character d, BTNode left1, BTNode right1){
c=d;left=left1;right=right1;
}
takes a Character
and assigns it to
char c;
this is technically legal because of autoboxing but when d
is null
it is equivalent to
c = ((Character) null).charValue()
which results in a NullPointerException
.
You shouldn't use Character
unnecessarily, so I would rework the calls to the constructor to
BTNode((char) 0, null, null)
and changes the signature of BTNode
to take a char
instead of a Character
, but you could also change c=d;
to
c = d != null ? d.charValue() : (char) 0;
精彩评论