二叉查找树是对树的一个经典的应用,下面使用Java实现对二叉查找树的各种实现,其中私有方法使用递归实现,然后公有方法调用私有方法,下面上代码
首先是作为二叉树的节点的类
package com.bird.four; /** * @category 二叉查找树的节点 * @author Bird * */ public class BinaryNode { Comparable<Object> element;//节点存储的数据 BinaryNode left;//二叉树的左孩子 BinaryNode right;//二叉树的右孩子 BinaryNode(Comparable<Object> theElement){ this(theElement,null,null); } BinaryNode(Comparable<Object> theElement, BinaryNode lt, BinaryNode rt){ element = theElement; left = lt; right = rt; } }
下面是二叉查找树的实现
package com.bird.four; /** * @category 二叉查找树的实现 * @author Bird * */ public class BinarySearchTree { private BinaryNode root;//二叉树的根节点 public BinarySearchTree(){ root = null; } public void makeEmpty(){ root = null; } public boolean isEmpty(){ return root == null; } private Comparable<Object> elementAt(BinaryNode t){ return t == null ? null : t.element; } /** * * @param x 需要查找的数据域 * @param t 初始为根节点,递归表示各个节点 * @return 找到的节点的引用 */ private BinaryNode find(Comparable<Object> x, BinaryNode t){ if(t == null) return null; if(x.compareTo(t.element) < 0) return find(x,t.left); else if(x.compareTo(t.element) > 0) return find(x,t.right); else return t; } /** * 寻找最小的节点直接一次向左递归就可以 * @param t * @return */ private BinaryNode findMin(BinaryNode t){ if(t == null) return null; else if(t.left == null) return t; return findMin(t.left); } /** * 同理,求最大值只需向右,但是不用递归 * @param t * @return */ private BinaryNode findMax(BinaryNode t){ if(t != null) while(t.right != null) t = t.right; return t; } /** * 插入算法的实现,递归找到位置后插入 * @param x * @param t * @return */ private BinaryNode insert(Comparable<Object> x, BinaryNode t){ if(t == null) t = new BinaryNode(x,null,null); else if(x.compareTo(t.element) < 0) t.left = insert(x,t.left); else if(x.compareTo(t.element) > 0) t.right = insert(x,t.right); else ; return t; } /** * 删除算法,其实现在使用懒惰删除,就是将需要删除的节点给一个标记 * @param x * @param t * @return */ private BinaryNode remove(Comparable<Object> x, BinaryNode t){ if(t==null) return t; if(x.compareTo(t.element) < 0) t.left = remove(x,t.left); else if(x.compareTo(t.element) > 0) t.right = remove(x,t.right); else if(t.left != null && t.right != null){//有两个孩子 t.element = findMin(t.right).element; t.right = remove(x,t.right); } else t = (t.left != null) ? t.left : t.right; return t; } private void printTree(BinaryNode t){ if(t != null){ printTree(t.left); System.out.println(t.element); printTree(t.right); } } public Comparable<Object> find(Comparable<Object> x){ return elementAt(find(x,root)); } public Comparable<Object> findMin(){ return elementAt(findMin(root)); } public Comparable<Object> findMax(){ return elementAt(findMax(root)); } public void insert(Comparable<Object> x){ root = insert(x,root); } public void remove(Comparable<Object> x){ root = remove(x,root); } public void printTree(){ printTree(root); } }