Definition: A binary search tree is a binary tree. It may be empty. If it is not empty then it satisfies the following properties:
Chapter 15 in text (page 568)
Examples in Figure 15.1. Note that all of the trees here are also valid Binary Search Trees.Since the definition of binary seach trees is recursive, it is easy to describe recursive methods.
There are always many ways to implement something (even binary trees). An
alternate implementation is on my web page [compliments of Jake {insert, delete, display (private find)}].
The text provides non-recursive methods
get(Object theKey) (Program 15.4), put(Object theKey, Object theElement) (Program 15.5), remove(Object theKey) (Program 15.6), and ascend()
The book uses Object as the Node, and theKey is also an Object. In the following example, I am just using Node and using "theKey" to be a String with
variable name
Here is the starter for a Binary Tree class (search first since it is easy to follow and the recursion is cool):
public Node search(String x){}
}
A recursive search method:
Why the public and private? (depends on what you want user to be able to do)
This could be done iteratively:
Consider doing a search with Java threads (thread for left subtree, thread for
right subtree). (Binary Tree vs Binary Search Tree) Code?
When the node to be deleted has two children, it can either be
replaced by the largest node on the left subtree or the smallest node on the
right subtree (to maintain binary tree properties).
Figure 15.4
Here is more to help consider.
word.
Class Structure: Node, BinTree
Let's start out with the Node class:
class BinTree{
private Node root;
private Node curNode; // depends on implementation
// preconditions: true (user calls correctly)
// postconditions: bt = #bt and if n is in bt the value returned is an instance of Node (n) where n.word = x else value returned is null
Search/Find/Get
Search method :
One will call this method on a binary tree instance -
say bt.search(x) looking for the key x. It will return the Node where x is the
key.
String.compareTo
Insert/Put
One needs to do inserts:
One at at time, and Figure 15.3
Delete/Remove
One needs to do deletes. Four situations are possible
update the parent node to have an empty subtree
attach the left subtree of D to the parent
attach the right subtree of D to the parent
tougher - choices are possible
Here is code to get started:
Complete this code. See text Program 15.6 if you need help.