1. 二叉排序树的定义
它或者是一棵空树;或者是具有下列性质的二叉树:
(1)若左子树不空,则左子树上所有结点的值均小于它的根结点的值;
(2)若右子树不空,则右子树上所有结点的值均大于它的根结点的值;
(3)左、右子树也分别为二叉排序树;
2. java实现代码(注:以下代码参考网上优秀代码,均已编写实现)
/*
* 注:该代码实现了二叉查找树的所有操作:包括,插入、删除、查找、排序输出、前驱、后继等。
* */
import java.util.ArrayList;
import java.util.List;
public class BinarySearchTree {
// 二叉查找树的根节点
private TreeNode root = null ;
private List<TreeNode> nodelist = new ArrayList<TreeNode>();
// 二叉树的节点类
private class TreeNode{
private int key ;
private TreeNode leftChild ;
private TreeNode rightChild ;
private TreeNode parent ;
// 构造器
public TreeNode(int key , TreeNode leftChild , TreeNode rightChild , TreeNode parent)
{
this.key = key ;
this.leftChild = leftChild ;
this.rightChild = rightChild ;
this.parent = parent ;
}
public int getKey()
{
return key ;
}
public String toString()
{
String leftkey = (leftChild == null ? "" : String.valueOf(leftChild.key));
String rightkey = (rightChild == null ? "" : String.valueOf(rightChild.key));
return "("+leftkey+","+key+","+rightkey+")";
}
}
/*
* 判断二叉查找树是否为空;若为空,返回true,否则返回false
* */
public boolean isEmpty()
{
if(root == null){
return true ;
}else{
return false ;
}
}
/*
* 对于某些二叉查找树操作(比如删除关键字)来说,若树为空,则抛出异常。
* */
public void TreeEmpty() throws Exception
{
if(isEmpty()){
throw new Exception("树为空!"