1. 二叉查找树
二叉查找树(Binary Search Tree)/ 有序二叉树(ordered binary tree)/ 排序二叉树(sorted binary tree)
1). 若任意节点的左子树不空,则左子树上所有结点的值均小于它的根结点的值;
2). 若任意节点的右子树不空,则右子树上所有结点的值均大于它的根结点的值;
3). 任意节点的左、右子树也分别为二叉查找树。
4). 没有键值相等的节点(no duplicate nodes)。
public class BinarySearchTree<AnyType extends Comparable<? super AnyType>>{ private static class BinaryNode<AnyType>{ BinaryNode(AnyType theElement){ this(theElement,null,null); } BinaryNode(AnyType theElement, BinaryNode<AnyType> lt, BinaryNode<AnyType>){ element=theElement; left=lt; right= rt; } AnyType element; BinaryNode<AnyType> left; BinaryNode<AnyType> right; } private BinaryNode<AnyType> root; //构造函数 public BinarySearchTree(){ root=null; } public void makeEmpty(){ root=null; } public booolean isEmpty(){ return root==null; } public boolean contains(AnyType x){ return contains(x,root); } public AnyType findMin() { if(isEmpty()) throw new UnderflowException(); return findMin(root).element; } public AnyType findMax() { if(isEmpty()) throw new UnderflowException(); return findMax(root).element; } public void insert(AnyType x){ root=insert(x,root); } public void remove(AnyType x){ root=remove(x,root); } public void printTree(){ if(isEmpty()) System.out.println("Empty tree"); else printTree(root); } //二叉树的contains操作 private boolean contains(AnyType x, BinaryNode<AnyType> t){ if(t==null) return false; //Comparable接口的compareTo方法比较两个值 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; } //查找最小值节点 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; } //insert插入,返回对 新树根的引用 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; } private void printTree(BinaryNode<AnyType> t){ if(t!=null) { printTree(t.left); System.out.println(t.element); printTree(t.right); } } }
时间: 2024-10-10 22:36:03