Hello everyone,
I am trying to implement this binary search tree using recursion.
On the first iteration of the loop within the driver class, the first record gets added as root just as I expected, but now on the second iteration within the driver class the root is overwritten with the second record before it even steps in to the insert method. Why is this happening?
Here is my code:
Main Driver Class:
import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; public class GolfCourseDriver { public static void main(String[] args) throws IOException { FileInputStream fstream = new FileInputStream("GolfCourseData.txt"); DataInputStream in = new DataInputStream(fstream); BufferedReader br = new BufferedReader(new InputStreamReader(in)); Tree searchTree = new Tree(); GolfCourse gcRec = new GolfCourse(); String strLine; int count = 1; String totalRecs = br.readLine(); // get total num of records // build each node from each golfCourseObject while((strLine = br.readLine()) != null){ switch(count){ case 1: gcRec.setCourseName(strLine); break; case 2: gcRec.setLocation(strLine); break; case 3: gcRec.setGreensFee(Double.valueOf(strLine)); break; case 4: gcRec.setPar(Integer.valueOf(strLine)); break; case 5: gcRec.setDesigner(strLine); break; case 6: gcRec.setYearBuilt(Integer.valueOf(strLine)); break; case 7: gcRec.setYards(Integer.valueOf(strLine)); break; default: System.out.println("Error! invalid item found."); break; } // reset count if(count == 7){ searchTree.insert(gcRec); count = 1; } else{ count++; } } in.close(); } }
Tree Class
public class Tree { private TreeNode root; public Tree() { root = null; } public void insert(GolfCourse object) { root = insert(object, root); } private TreeNode insert(GolfCourse newObject, TreeNode node) { if (node == null) { return new TreeNode(newObject); } if (newObject.greensFee == node.object.greensFee) { // replace the value in this node with a new value node.object = newObject; // alternative code creates new node, leaves old node unchanged: //return new BinaryNode<T>(value, node.left, node.right); } else { if (newObject.greensFee < node.object.greensFee) { // add to left subtree node.lPtr = insert(newObject, node.lPtr); } else { // add to right subtree node.rPtr = insert(newObject, node.rPtr); } } return node; } }
Tree Node Class:
public class TreeNode { GolfCourse object; TreeNode lPtr; TreeNode rPtr; public TreeNode() { } public TreeNode(GolfCourse data){ object = data; } }
First few records of text Data passed in "GolfCourseData.txt:
22 Abacoa Golf Club Jupiter 45 72 Joe Lee 1999 7200 Eastpointe Country Club PB Gardens 50 72 George and Tom Fazio 1974 6890
Thanks