View Single Post
  #1 (permalink)  
Old 04-29-2007, 12:58 AM
invincible_me invincible_me is offline
Member
 
Join Date: Apr 2007
Posts: 1
invincible_me is on a distinguished road
help needed regarding tree building
hey friends

I am facing problem converting a code that reads a file with a number in different line eg
6
4
7
8
2

then building a tree(binary search tree) from this input file. the code i wrote is:

Code:
import java.util.*; import java.io.*; public class des { public static void main(String[] args)throws IOException { String s=null; DataInputStream dis=new DataInputStream(System.in); System.out.println("Enter the name of the file"); try { s = dis.readLine(); } catch(IOException e) { System.out.println("Nothing has been entered, please enter something"); } //function(s); new des().run(s); } static class Node { Node left; Node right; int value; public Node(int value) { this.value = value; } } public void run(String fn)throws IOException { int q=-1,i=0; int a[]=new int[100]; Node root=null; FileReader fr; BufferedReader bf=null; String line,str=null; System.out.println("Filename is "+fn); // try // { fr=new FileReader(fn); bf=new BufferedReader(fr); while((line=bf.readLine()) !=null) { StringTokenizer st = new StringTokenizer(line); //while(st.hasMoreTokens()) //{ q++; try { str=st.nextToken(); a[i]=Integer.parseInt(str); } catch(NumberFormatException e) { System.out.println(str+ " is not in the right format"); System.out.println(); q--; continue; } if(q==0) { root = new Node(a[i]); System.out.println("Building tree with root value " + root.value); } if(i>0) insert(root,a[i]); i++; } } public void insert(Node node, int value) { if (value < node.value) { if (node.left != null) { insert(node.left, value); } else { System.out.println(" Inserted " + value + " to left of "+ node.value); node.left = new Node(value); } } else if (value > node.value) { if (node.right != null) { insert(node.right, value); } else { System.out.println(" Inserted " + value + " to right of "+ node.value); node.right = new Node(value); } } } }
The problem is i want to convert this code to a code which takes as input a file like

6 6
4 6
3 6
2 4
1 4
2 3

where the first number in a line is a child and the second number is the parent of that child. the first line indicates that 6 is a root node.

kindly help me in changing the code above for this input.

thanks in anticipation
Reply With Quote
Sponsored Links