why does this create a null point exception
public ArrayList<K> keysAsList(){
ArrayList<K> temp =new ArrayList<K>();
MapNode t = root;
if (root !=null)
keysAsList(temp, t);
return temp;
}
privatevoid keysAsList(ArrayList<K> t, MapNode x){
t.add(x.key);
keysAsList(t, x.left);
keysAsList(t, x.right);
}
You have a recursive function that invokes itself with x.left and x.right. The first thing you do with the passed in value is to get the key (x.key) but if x.left is null or x.right is null then x.key must produce a NPE.
If I were doing this I would put a guard in the method keysAsList(ArrayList<K> t, MapNode x) like
if (x == null)
return;
then you will not need the if (root != null)