Hi i`m new to java however i have been given a piece of coursework. What it wants me to do is basically store strings in a binery tree however when i test it my count method does not seem to be working what its supposed to do is see how many times a particular string appearers in the tree.Is it possible someone can modify my count method so its correct thanks.
import java.util.*;
//node of the binary tree
class WordStore {
String word;
WordStore left;
WordStore right;
int b;
WordStore root;
WordStore() {
word = null;
left = null;
right = null;
}
public WordStore(String word) {
this.word = word;
left = null;
right = null;
root = null;
}
public WordStore(int a)//doenst compile without it
{
b = a;
}
//binary tree
//insert a node into the tree
public void add(String word)
{
WordStore current = root;
WordStore prev = current;
if (root == null)
{
root = new WordStore(word);
}
else
{
boolean insert = false;
while (insert == false)
{
prev = current;
if (word.compareTo(current.word) < 0)
{
if (current.left == null)
{
current.left = new WordStore(word);
insert = true;
}
current = current.left;
}
else
{
if (current.right == null)
{
current.right = new WordStore(word);
insert = true;
}
current = current.right;
}
}
}
}
//delete a node with a word
public void remove(WordStore node, String word) {
// Task2 temp ,prev = null;
// boolean deleted = true;
WordStore current = root;
WordStore prev = current;
if(node != null && node.word.equals(word)){
if(node.right==null)
node=node.left;
else if (node.left==null)
node =node.right;
else{
current =node.left;
while(current.right != null)
current = current.right;
current.right=node.right;
node = node.left;
}
if (node==root)
root = node;
else if (prev.left == root )
prev.left = node;
else prev.right = node ;
}
else if (root != null)
System.out.println(word + "is not in the tree ");
else System.out.println("the tree is empty");
}
// public int count(String word)
public int count(String word)
{ int i=0;
WordStore current = root;
WordStore prev = current;
while (current != null)
{
if (word.compareTo(current.word) > 0)
{
prev = current;
current = current.right;
i++;
}
else if (word.compareTo(current.word) < 0)
{
prev = current;
current = current.left;
i++;
}
else if (word.compareTo(current.word) == 0)
{
break;
}
}
return i;
}
}