Related Notes: Trees - CS2400
Binary Search Tree: A binary tree where each node’s value is:
Limitation: Unique keys only.
Note: Each node in a BST is the root of another BST.
public interface SearchTreeInterface<T extends Comparable<? super T>> extends TreeInterface<T> {
boolean contains(T anEntry);
getEntry(T anEntry);
T add(T anEntry);
T remove(T anEntry);
T Iterator<T> getInorderIterator();
}
Remember: Inorder traversal is the only traversal that makes sense for BST.
If any entry e has a duplicate entry d, we arbitrarily require that d occur in the right subtree of e’s node.
Algorithm bstSearch(tree, needle) {
if tree is empty
return false
else if needle == root
return true
else if needle < root
return bstSearch(tree's left subtree, needle)
else needle > root
return bstSearch(tree's right subtree, needle)
}
To ensure that the BST is still valid:
Algorithm for Removing a Node that has Two Children:
add
, remove
, and getEntry
are O(h)
The most inefficient tree will have O(n)
The most efficient tree will have O(\log n)