I have to write code for a collection of values using a binary tree, one of the methods is a belongs method to see if the value the user inputs is in the collection. It returns true if the value is in the collection and false if its not. I wrote a main method to test it but every time I run it I get false even if the values in the collection. To me the code I wrote seems like it should work, but obviously that is not the case, so I decided to post it here to see if I could get some help on this. I also need help on a print method for printing the values in the binary tree, but Ill just take it one method at a time for now :D
Thanks
I dont know if you need this, but its the main method I wroteCode:public class Intcoll6
{
private btNode c;
private int how_many;
public Intcoll6()//default constructor
{
c = null;
how_many = 0;
}
public Intcoll6(int i)// alt constructor
{
c = null;
how_many = 0;
}
public boolean belongs(int i)// This is where I am having trouble should return true if the values in the binary tree
{
btNode p = c;
while((p != null) && (p.info != i))
{
if(i < p.info)
{
p = p.lt;
}
else
{
p = p.rt;
}
}
return (p != null);
}
public void insert(int i)// inserts a value into the binary tree
{
btNode p = c, q = null;
while((p != null) && (p.info != i))
{
q = p;
if(i < p.info)
{
p = p.lt;
}
else
{
p = p.rt;
}
}
if(p == null)
{
how_many++;
p = new btNode();
p.info = i;
if(q != null)
{
if(i < q.info)
{
q.lt = p;
}
else
{
q.rt = p;
}
}
}
else
{
c = p;
}
}
public int get_howmany()//counts the amount of values in the collection
{
return how_many;
}
public void print(btNode p)//prints out the collection, not sure how to do this yet, any help would be appreciated :)
{
}
private class btNode
{
private int info;
private btNode lt;
private btNode rt;
public btNode()
{
info = 0;
lt = null;
rt = null;
}
}
}
Code:import java.util.Scanner;
public class Intcoll6testclient
{
public static final int SENTINEL = 0;
public static void main(String[] args)
{
int value;
int val2;
Scanner keyboard=new Scanner(System.in);
Intcoll6 P = new Intcoll6();
System.out.println("Enter an integer to be inserted or 0 to quit:");
value=keyboard.nextInt();
while(value != SENTINEL)
{
P.insert(value);
System.out.println("Enter next integer to be inserted or 0 to quit:");
value=keyboard.nextInt();
}
System.out.println("Type a value to see if it belongs in the collection: ");
val2 = keyboard.nextInt();
System.out.println("The Method returned: " + P.belongs(val2));
}
}

