Skip to content

Instantly share code, notes, and snippets.

@Deathnerd
Created November 15, 2015 06:26
Show Gist options
  • Save Deathnerd/9cf2a32cabf2f1fd5cbf to your computer and use it in GitHub Desktop.
Save Deathnerd/9cf2a32cabf2f1fd5cbf to your computer and use it in GitHub Desktop.
A Queue approach to Breadth-First searching of a binary tree
/**
* Searches through the current tree for a given key. Will return a match if
* a node exists that has a value that starts with key or is equal to key.
* All comparisons are in lowercase.
*
* @param key The key containing the value to search for
* @return The node if it finds it
* @throws EmptyTreeException If the current tree is empty
* @throws NodeNotFoundException If the node isn't found
*/
public BinarySearchTreeNode<K> search(K key) throws EmptyTreeException, NodeNotFoundException {
if (this.root == null) {
throw new EmptyTreeException();
}
LinkedList<BinarySearchTreeNode<K>> node_queue = new LinkedList<>();
BinarySearchTreeNode<K> current;
node_queue.add(this.root);
String key_string = key.toString().toLowerCase();
while (!node_queue.isEmpty()) {
current = node_queue.pop();
String current_string = current.toString().toLowerCase();
if (current_string.equals(key_string) || current_string.startsWith(key_string)) {
return current;
}
if (current.left != null) {
node_queue.add(current.left);
}
if (current.right != null) {
node_queue.add(current.right);
}
}
throw new NodeNotFoundException();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment