I'm trying to provide a public method that builds a Binary Search Tree based on an input file of an unknown number of positive integers, one per line. The problem is, from my little knowledge/experience, I cannot utilize recursion because it is required to prompt the user for an input file within the method. This must also be the only method created.
This is the TreeNode class:
public static class TreeNode
{
TreeNode LeftLink;
int Content;
TreeNode RightLink;
}
// end class TreeNode
And here is the code I have so far:
public static TreeNode BuildSearchTree() throws IOException
{
TreeNode T = new TreeNode();
//Prompt User for FileName
System.out.println("Enter file name:");
Scanner Scan = new Scanner(System.in);
String FileName = Scan.next();
Scanner InFile = new Scanner (new File(FileName));
int Key = 0;
//Create Binary Search Tree
while(InFile.hasNext())
{
Key = InFile.nextInt();
if (Key < T.Content)
if (T.LeftLink != null)
{
T = T.LeftLink;
}
//end if
else
{
//System.out.println(" Inserted " + Key + " to left of Node " + T.Content);
T.LeftLink = new TreeNode();
T.LeftLink.Content = Key;
}
//end if
else if (Key > T.Content)
if (T.RightLink != null)
{
T = T.RightLink;
}
//end if
else
{
//System.out.println(" Inserted " + Key + " to right of Node " + T.Content);
T.RightLink = new TreeNode();
T.RightLink.Content = Key;
}
//end else if
}
//end while
return T;
}
// end method BuildSearchTree
I can see the problem is I'm not adding additional "Nodes" to the Tree. I'm a little stumped as to how to do this, any help in the right direction would be greatly appreciated!

New Topic/Question
Reply




MultiQuote







|