Problem with Binary Search Tree
Hi, I'm new to the forum and am not sure if this is the right place to post this, but I'm getting a problem with the following Binary Search Tree:
Code :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Comparator;
class BST{
private BSTNode t=null;
private BSTNode l = null;
private BSTNode r = null;
private BSTNode node;
private StringComparator comp;// how to compare nodes
public BST(Comparator c){
}
// constructor
public BSTNode insert(Object newData){
BSTNode temp=t;
if (t == null)
{
t=new BSTNode(newData);
t.left= new BSTNode(null);
t.right= new BSTNode(null);
return t;
}
else
{
while (temp.data != null)
{
if (comp.compare(temp.data, newData)<0)
{
System.out.println("going left");
temp=temp.left;
}
else
{
System.out.println("going right");
temp=temp.right;
}
}
temp.data=newData;
temp.left= new BSTNode(null);
temp.right= new BSTNode(null);
return temp;
}
// if (comp.compare(t.data, newData)<0)
// return t.left = insert(newData);
//else return t.right = insert(newData);
}
// can check if comp is null before insert
public void setComparator(StringComparator c){
if (t == null)
c.compare(t.data, node.data);
}
// only allow if tree empty
public void clear(){
t = null;
}// empty tree
public BSTNode find(String key)
{
if (t == null)
return null;
if (key == t.data)
return t;
if (comp.compare(key, t.data)<0)
return find(key);
else
return find(key);
}
public void getText(JTextField t, String key)
{
t.setText(key);
}
public String toString()
{
String fail= "The object was not found.";
return fail;}
}
In particular I'm getting a null pointer exception on line 33 (if (comp.compare(temp.data, newData)<0)).
Any idea why this is happening? Help would be much appreciated!
Re: Problem with Binary Search Tree
Use the System.println method and add some println's in there to monitor the command line and see what object on that line could be null. NullPointerException indicates a reference is null...so when you find anything that is null, backtrack and make sure it is assigned properly (either to a valid reference or creating a new one). For future reference, posting an SSCCE with descent indenting helps
Re: Problem with Binary Search Tree
And please be forthright when crossposting - many (including myself) do not appreciate writing responses to posts which may have been answered or discussed elsewhere without their knowledge
This thread has been cross posted here:
http://www.java-forums.org/new-java/58889-problem-binary-search-tree.html
Although cross posting is allowed,
for everyone's benefit, please read:
Java Programming Forums Cross Posting Rules
The Problems With Cross Posting