# Thread: Help. Binary Search Problem

1. Member
Join Date
Nov 2008
Posts
43
Rep Power
0

## [SOLVED] Help. Binary Search Problem

Hello, I need to make a binary search tree for another program that counts words in documents. When the word counting program gets to the lines:
Java Code:
```try {
Integer freq = M.search(word);
M.modify(word,freq+1);
}
catch(KeyNotFoundException e) {
M.insert(word,1);
}```
The search function in my binary tree class throws a Key not found exception so it than tries to add it from scratch but my insert function does find it and throws KeyFound Exception. Here are the functions from my program:
Java Code:
``` /**
* Inserts a key-value pair into the map.
* @param key The key to be inserted.
* @param value Key's corresponding value.
* @throws KeyFoundException If a matching key is
* already present in the map
*/
public void insert (K key, V value) throws KeyFoundException {
if (isEmpty())  {head = new Node <K, V> (key, value, null, null);}
else  {
Node <K, V> current = head;
while (true) {
if ((current.key).compareTo(key) == 0)  {throw new KeyFoundException ();}
else if ((current.key).compareTo(key) > 0)  {
if (current.rightNode != null) {current = current.rightNode;}
else {current.rightNode = new Node <K, V> (key, value, null, null);}
}
else if ((current.key).compareTo(key) < 0)  {
if (current.leftNode != null) {current = current.leftNode;}
else {current.leftNode = new Node <K, V> (key, value, null, null);}
}
}
}
treeSize++;
}```
Java Code:
```/**
* Returns the value corresponding to key.
* @param key The key to search for in the map.
* @returns V The value corresponding to key.
* in the map.
*/
public V search (K key) throws KeyNotFoundException {
Node <K, V> current = head;
while (current != null) {
if ((current.key).compareTo(key) == 0)  {
return current.value;}
else if((current.key).compareTo(key) > 0)  {
current = current.rightNode;}
else if((current.key).compareTo(key) < 0)  {
current = current.leftNode;}
}
throw new KeyNotFoundException ();
}```
Does anyone have any idea why the search function can not find the key but the insert function does find the key?
Thank You for any help.

EDIT: I didnt have a return in my Search function, so it would add it, loop again and find the same entry. Silly mistake.
Last edited by Krooger; 11-03-2008 at 07:21 AM. Reason: Solved...

2. You have question here and you solved it your self. It's nice. So you no need to delete it, because you can help to your community on that. Post the way you solved it, then if someone else have the same problem, he/she can refer you thread and solve there questions.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•