二叉查找树的实现(可执行代码)
import java.util.Scanner; public class BSTree<AnyType extends Comparable<? super AnyType>>{ BiNode root; class BiNode<AnyType>{ AnyType data; BiNode left; BiNode right; public BiNode(AnyType data){ this.data=data; } public BiNode(AnyType data,BiNode left,BiNode right){ this.data=data; this.left=left; this.right=right; } } //添加 public void insert(AnyType x){ root=insert(x,root); } public BiNode insert(AnyType x,BiNode t){ if(t==null) return new BiNode(x,null,null); int compareResult=x.compareTo((AnyType)t.data); if(compareResult>0) t.right=insert(x,t.right); if(compareResult<0) t.left=insert(x,t.left); else; return t; } //找最小 public AnyType findMin(){ return (AnyType) findMin(root).data; } public BiNode findMin(BiNode t){ if(t==null) return null; else if(t.left==null) return t; else return findMin(t.left); } //删除 public void remove(AnyType x){ root=remove(x,root); } public BiNode remove(AnyType x,BiNode t){ if(t==null) return t; int compareResult=x.compareTo((AnyType)t.data); 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.data=findMin(t.right).data; t.right=remove((AnyType)t.data,t.right); } else t=(t.left!=null)?t.left:t.right; return t; } //中序遍历 public void inOrder(){ inOrder(root); } public void inOrder(BiNode t){ if(t!=null){ inOrder(t.left); System.out.print(t.data+" "); inOrder(t.right); } } public static void main(String[] args) { Scanner sc=new Scanner(System.in); BSTree<Integer> bsh=new BSTree<Integer>(); for(int i=0;i<6;i++){ int numble=sc.nextInt(); bsh.insert(numble); } bsh.inOrder(); } }
版权声明:本文为博主原创文章,未经博主允许不得转载。