package edu.cumt.tree.binary;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Stack;
public class BinarySortTree <E> {
/**定义树的根节点*/
private TreeNode root;
/**默认的元素比较器,当一个类创建之后比较器不可以更换*/
private Comparator<E> comp=new Comparator<E>(){
@Override
public int compare(E key, E elem) {
int n1=key.hashCode();
int n2=elem.hashCode();
return (n1>n2)?1:(n1==n2)?0:-1;
}
};
public BinarySortTree(){
root=null;
}
public BinarySortTree(Comparator <E>comp ){
this.comp=comp;
root=null;
}
/**向树集合中插入元素,当元素小于根节点时,插入到左子树上,否则插入到右子树上,
* 如果所插入的元素存在,则放回false,否则返回true*/
public boolean insert(E key){
TreeNode p,next;
p=next=root;
boolean left=false;
while(next!=null){
if(key.equals(next.element)){
return false;
}else if(comp.compare(key,next.element)<0){
p=next;
next=next.left;
left=true;
}else{
p=next;
next=next.right;
left=false;
}
}
if(p==null){
root=new TreeNode(key);
}else if(left){
p.left=new TreeNode(key);
}else {
p.right=new TreeNode(key);
}
return true;
}
/**判断指定的值是否在当前的树结合中*/
public boolean contain(E key){
TreeNode next=root;
while(next!=null){
if(key.equals(next.element)){
return true;
}else if(comp.compare(key,next.element)<0){
next=next.left;
}else{
next=next.right;
}
}
return false;
}
/**将指定的元素丛树中移除掉成功返回true,否则返回false*/
public boolean remove(E key){
TreeNode p=root,next=root;
while(next!=null){
if(key.equals(next.element)){
if(next.left==null||next.right==null)
break;
TreeNode min=next.right;
while(min.left!=null){
min=min.left;
}
next.element=min.element;
key=min.element;
p=next;
next=next.right;
}else if(comp.compare(key,next.element)<0){
p=next;
next=next.left;
}else{
p=next;
next=next.right;
}
}
if(next==null)
return false;
TreeNode temp;
if(next.right==null){
temp=next.left;
}else{
temp=next.right;
}
if(p.left==next){
p.left=temp;
}else if(p.right==next){
p.right=temp;
}else{
root=temp;
}
return true;
}
/**迭代数中的元素按照前序遍历的顺序*/
public Iterator<E> iterator(){
return new Iterator<E>(){
Stack<TreeNode> stack= new Stack<TreeNode>();
TreeNode next=root;
@Override
public boolean hasNext() {
while(next==null){
if(stack.isEmpty()){
return false;
}
next=stack.pop();
next=next.right;
}
return true;
}
@Override
public E next() {
stack.push(next);
E obj=next.element;
next=next.left;
return obj;
}
@Override
public void remove() {
throw new UnsupportedOperationException(BinarySortTree.class.getName()+" 的迭代不支持这个方法!");
}
};
}
/**定义一个树的节点元素*/
private class TreeNode{
TreeNode(E elem){
this.element=elem;
left=null;
right=null;
}
E element;
TreeNode left;
TreeNode right;
}
}