/*二叉查找树 2017-1-3 adr daoyuan */ public class BinarySearchTree<AnyType extends Comparable<? super AnyType>> { //嵌套类--定义节点的有关性质 private static class BinaryNode<AnyType>{ AnyType element; BinaryNode<AnyType> left; BinaryNode<AnyType> right; BinaryNode(AnyType theElement){ this(theElement,null,null);} BinaryNode(AnyType theElement,BinaryNode<AnyType> lt,BinaryNode<AnyType> rt){ element=theElement; left=lt; right=rt; } } private BinaryNode<AnyType> root; public BinarySearchTree(){ root=null; } public void makeEmpty(){root=null;} public boolean isEmpty(){ return root==null; } //contains函数的书写; public boolean contains(AnyType x){ return contains(x,root); } private boolean contains(AnyType x,BinaryNode<AnyType> 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 AnyType findMin(){ if(isEmpty()) throw new RuntimeException("树为空"); return findMin(root).element; } private BinaryNode<AnyType> findMin(BinaryNode<AnyType> t){ if(t==null) return null; else if(t.left==null)return t; return findMin(t.left); } private BinaryNode<AnyType> findMax(BinaryNode<AnyType> t){ if(t!=null) while (t.right!=null) t=t.right; return t; } public void insert(AnyType x){ root=insert(x,root); } private BinaryNode<AnyType> insert(AnyType x,BinaryNode<AnyType>t){ if(t==null) return new BinaryNode<AnyType>(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; } private BinaryNode<AnyType> remove(AnyType x,BinaryNode<AnyType>t){ if(t==null) return t; 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.element=findMin(t.right).element; t.right=remove(t.element,t.right); }else t=(t.left!=null)?t.left:t.right; return t; } //二叉树的遍历,按照顺序,先左字树,节点,再右子树 public void printTree(BinaryNode<AnyType> t){ if(t!=null){ printTree(t.left); System.out.println(t.element); printTree(t.right); } } public void printTree(){ if(isEmpty()){ System.out.println("Empty tree"); }else printTree(root); } public static void main(String[] args){ // BinaryNode binaryNode=new BinaryNode("A"); BinarySearchTree binarySearchTree=new BinarySearchTree(); binarySearchTree.insert("1"); binarySearchTree.insert("5"); binarySearchTree.insert("3"); binarySearchTree.insert("7"); binarySearchTree.printTree(); } }
二叉查找树
最新推荐文章于 2024-09-13 16:27:15 发布