I am having a bit of trouble with this binary search tree program. What I have to do is this:
Write a main program that allows the user to choose among the following options:
- enter a new string into the tree
- find if a string is already in the tree
- print an alphabetical list of all strings in the tree
I have the code mostly done and it is:
public class BTNode { public String data; public BTNode left; public BTNode right; public BTNode(String data, BTNode l, BTNode r) { this.data = data; this.left = l; this.right = r; } public BTNode(String data) { this.data = data; } }
public class BTree { public BTNode root; public BTree(){ } public BTree(BTree t){ CopyNodes(t.root, this); } public void CopyNodes(BTNode node, BTree tree){ if(node == null){ return; } tree.insert(node.data); CopyNodes(node.left, tree); CopyNodes(node.right, tree); } public void insert(String newData){ root = insert2(newData, root); } public BTNode insert2(String s, BTNode n){ if(n == null){ return new BTNode(s); } if(s.compareTo(n.data) < 0){ n.left = insert2(s, n.left); }else if(s.compareTo(n.data) > 0){ n.right = insert2(s, n.right); } return n; } public BTNode find(String s){ BTNode node = root; while(node != null){ if(s.equals(node.data)){ return node; } if(s.compareTo(node.data) < 0){ node = node.left; }else{ node = node.right; } } return null; } public void printInOrder(){ printInOrder2(root); } public void printInOrder2(BTNode n){ if(n == null) return; printInOrder2(n.left); System.out.println(n.data); printInOrder2(n.right); } }
and the driver program
import java.util.*; public class TreeDriver { public static void main(String args[]) { BTree t = new BTree(); Scanner scan = new Scanner(System.in); do{ System.out.println("Please select one of the following."); System.out.println("To insert something into the Tree press 1."); System.out.println("To check if something is already in the tree press 2."); System.out.println("To print the tree in alphabetic order press 3."); System.out.println("To exit press 4."); if (scan.nextInt() ==1) { System.out.println("Please enter a word"); t.insert(scan.next()); System.out.println("Press 1 to return to selections"); } else if (scan.nextInt() ==2) { System.out.println("Enter the word to check"); t.find(scan.next());} else if (scan.nextInt() ==3) { System.out.println("The tree in alphabetic order is: "); t.printInOrder();} else if (scan.nextInt()==4) System.out.println("program ending"); } while(scan.nextInt()!=4); } }
my problem is that I am unsure how to get a message to come up if you try to insert something in the tree that is already there, and for my driver program It works but it only works if you enter the commands several times. I know it is a problem with how I set up my loop but I can't think of a better way to do this.