public class BinarySearchTree<T extends Comparable<? super T>> {
public static class BinaryNode<T> {
public BinaryNode(T element) {
this(element, null, null);
}
public BinaryNode(T element, BinaryNode<T> lt, BinaryNode<T> rt) {
this.element = element;
left = lt;
right = rt;
}
private T element;
private BinaryNode<T> left;
private BinaryNode<T> right;
}
private BinaryNode<T> root;
public BinarySearchTree() {
root = null;
}
public void makeEmpty() {
root = null;
}
public boolean isEmpty() {
return (root == null);
}
public boolean contains(T x) {
return contains(x, root);
}
public boolean contains(T x, BinaryNode<T> node) {
if(node == null){
return false;
}
int compareResult = x.compareTo(node.element);
if(compareResult < 0){
return contains(x,node.left);
}else if(compareResult > 0){
return contains(x,node.right);
}else{
return true;
}
// return false;
}
public T findMin() {
if (isEmpty()) {
try {
throw new UnderflowException();
} catch (UnderflowException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return findMin(root).element;
}
private BinaryNode<T> findMin(BinaryNode<T> node) {
if(node == null){
return null;
}else if(node.left == null){
return node;
}
return findMin(node.left);
}
public T findMax() {
if (isEmpty()) {
try {
throw new UnderflowException();
} catch (UnderflowException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return findMax(root).element;
}
private BinaryNode<T> findMax(BinaryNode<T> node) {
if(node == null){
return null;
}else if(node.right == null){
return node;
}
return findMax(node.right);
}
public void insert(T value) {
root = insert(value, root);
}
private BinaryNode<T> insert(T value, BinaryNode<T> root) {
if(root == null){
return new BinaryNode(value,null,null);
}
int compareResult = value.compareTo(root.element);
if(compareResult < 0){
root.left = insert(value,root.left);
}else if(compareResult > 0){
root.right = insert(value, root.right);
}
return root;
}
public void remove(T value){
root = remove(value,root);
}
private BinaryNode<T> remove(T value, BinaryNode<T> root) {
if(root == null){
return root;
}
int compareResult = value.compareTo(root.element);
if(compareResult < 0){
root.left = remove(value,root.left);
}else if(compareResult > 0){
root.right = remove(value,root.right);
}else if(root.left != null && root.right != null){
root.element = findMin(root.right).element;
root.right = remove(root.element,root.right);
}else{
root = (root.left != null)? root.left:root.right;
}
return root;
}
public void printTree(){
}
}