makeEmpty (): 使树为空;
isEmpty():判断是否为空
contains(T x):判断树中是否包含x
insert(T x):插入
remove(T x):删除
findMin();
findMax();
printTree():前序遍历。
public class BinarySearchTree <T extends Comparable<? super T>>{
private class Node <T>{
T element;
Node<T> left;
Node<T> right;
public Node(T element) {
super();
this.element = element;
}
public Node(T element, Node<T> left, Node<T> right) {
super();
this.element = element;
this.left = left;
this.right = right;
}
}
Node<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,Node<T> t) {
if(t==null) {
return false;
}
int compareResult=x.compareTo(t.element);
if(compareResult<0) {
return contains(x,t.left);
}
else if(compareResult>0) {
return contains(x,t.right);
}
else {
return true ;
}
}
public void insert(T x) {
root=insert(x,root);
}
public Node<T> insert(T x, Node<T> t) {
if(t==null) {
return new Node<T>(x,null,null);
}
int compareResult=x.compareTo(t.element);
if(compareResult<0) {
t.left=insert(x,t.left);
}
else if(compareResult>0) {
t.right=insert(x,t.right);
}
else {
;
}
return t;
}
public T findMin() {
return findMin(root).element;
}
public Node<T> findMin(Node<T> t) {
if(t==null)
return null;
else if(t.left==null) {
return t;
}
return findMin(t.left);
}
public T findMax() {
return findMax(root).element;
}
public Node<T> findMax(Node<T> t){
if(t==null)
return null;
else
{
while(t.right!=null)
t=t.right;
}
return t;
}
public void remove(T x) {
root=remove(x,root);
}
public Node<T> remove(T x ,Node<T> t){
if(t==null)
return null;
int compareResult=x.compareTo(t.element);
if(compareResult<0) {
t.left=remove(x,t.left);
}
else if(compareResult>0) {
t.right=remove(x,t.right);
}
else if(t.left!=null&&t.right!=null) {
T min=findMin(t.right).element;
t.element=findMin(t.right).element;
t.right=remove(min,t.right);
}
else
t=(t.left!=null)?t.left:t.right;
return t;
}
public void printTree() {
//前序遍历
printTree(root);
}
public void printTree(Node<T> t) {
if(t!=null) {
System.out.println(t.element);
printTree(t.left);
printTree(t.right);
}
}
}