Reputation: 11
I'm relatively new to Java, and am currently learning about implementing trees in Java, specifically Binary Search trees. Right now, most of what I have done has worked fine (Inorder and Postorder traversals, switching nodes, etc.), except for one important detail: 0 is added to my tree, even though I never inserted it. In other words, when I call for the inorder traversal of 45 9 2 100 4, I get 0 2 4 9 45 100. Here is the relevant code:
From the main function:
Scanner sc=new Scanner(System.in);
int m, n, j;
treenode T1=new treenode();
System.out.println("How many numbers will be entered?");
m=sc.nextInt();
System.out.println("Enter "+m+" integers.");
for(j=0;j<m;j++){
n=sc.nextInt();
T1.insert(T1, n);
}
System.out.println("Tree T1, in inorder sequence:");
T1.Inorder(T1);
etc.
And the function calls:
class treenode{
int data; treenode left; treenode right;
public treenode() {};
public treenode(int j)
{data = j; left = null; right = null;}
// Insert node function
public treenode insert(treenode t, int k){
if (t == null)
{t = new treenode();
t.data = k; t.left=null;
t.right=null; return t;}
else{
if( k > t.data)
{t.right = insert(t.right,k);
return t;}
else{t.left = insert(t.left, k);
return t;}}}
// Inorder traversal function
public void Inorder(treenode t){
if(t != null){
Inorder(t.left);
System.out.println(" " + t.data);
Inorder(t.right);}
}
etc.
And yes, I know, I need to change the class name to Treenode so it starts with a capital letter; I'll be doing that shortly.
Upvotes: 0
Views: 60
Reputation: 11
I went a different route to solve it (but you were both right, the initialization of the tree was the problem). I took the first node out of the for loop to initialize the tree with the first data point as follows:
treenode T1=new treenode(n);
for(j=1;j<m;j++){
n=sc.nextInt();
T1.insert(T1, n);
}
And now everything seems to be running smoothly. Thanks!
Upvotes: 1
Reputation: 22989
treenode T1=new treenode();
This creates a node with the value 0, not an empty tree. Representing an empty tree is tricky; the value null
won't work with the current implementation because it calls T1.insert()
, which will throw a null pointer exception.
One option is to make insert()
static by adding the static
modifier to the declaration, and changing the call to
T1 = treenode.insert(T1, n);
A similar thing would have to be done for Inorder()
, otherwise an explicit null check is required by the caller.
Another option is to create a wrapper class, Tree
, which has a root node (that can be null
). This would make the external interface cleaner:
T1.insert(n);
T1.Inorder();
As an aside, by convention classes and interfaces start with capital letters in Java while methods and variables start with a lower case letter. Following the convention helps others understand your code.
Upvotes: 1
Reputation: 1034
treenode T1=new treenode();
This line creates a root node with no data value (default to 0), so you always have 0 as the root of your tree.
Upvotes: 1