public class BinarySearchTree {
private BinarySearchTree left;
private BinarySearchTree right;
private int data;
public BinarySearchTree() {
left = null;
right = null;
}
/** Create a tree that consists of just one node with no children. */
public BinarySearchTree(int data) {
left = null;
right = null;
this.data = data;
}
/** Adds new number n to this BinarySearchTree, placing it in its correct place.
*
* @param n the number to be added
*/
public void add (int n) {
if (n <= data) {
if (left != null)
left.add(n);
else
left = new BinarySearchTree(n);
}
else { // n > data
if (right != null)
right.add(n);
else
right = new BinarySearchTree(n);
}
}
/** Returns the maximum number in this tree. */
public int max() {
if (right == null)
return data;
return right.max();
}
/** Returns the height of this tree. */
public int height() {
//The base cases are when a child is null.
return 1 + Math.max((left == null ? 0: left.height()),
(right == null ? 0: right.height()));
}
}
Tuesday, November 17, 2009
Homework 8 Solution
Below is my solution for the Binary Search Tree:
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment