1 什么是二分搜索树
二分搜索树,也叫二叉查找树(Binary Search Tree),有序二叉树(ordered binary tree),排序二叉树(sorted binary tree),是指一棵空树或者具有下列性质的二叉树:
若任意节点的左子树不空,则左子树上所有结点的值均小于它的根结点的值;
任意节点的右子树不空,则右子树上所有结点的值均大于它的根结点的值;
任意节点的左、右子树也分别为二叉查找树。
没有键值相等的节点(no duplicate nodes)。
二叉查找树的性质:
二叉查找树本质上是一种二叉树,所以上章讲的二叉树的性质他都有。
2 二叉搜索树的思想
二叉排序树的查找过程和次优二叉树类似,通常采取二叉链表作为二叉排序树的存储结构。中序遍历二叉排序树可得到一个关键字的有序序列,一个无序序列可以通过构造一棵二叉排序树变成一个有序序列,构造树的过程即为对无序序列进行排序的过程。每次插入的新的结点都是二叉排序树上新的叶子结点,在进行插入操作时,不必移动其它结点,只需改动某个结点的指针,由空变为非空即可。搜索,插入,删除的复杂度等于树高,O(log(n)).
3 实现 –简化版
package tree;
import java.util.LinkedList;
/**
* 二分搜索树
*
* @author xld
*
* @param <Key>
* @param <Value>
*/
public class BST<Key extends Comparable<Key>, Value> {
/**
* 树中的节点 设置为内部类
*
* @author xld
*
*/
private class Node {
private Key key;
private Value value;
private Node left, right;
public Node(Key key, Value value) {
this.key = key;
this.value = value;
left = right = null;
}
}
private Node root;
private int count;
public BST() {
root = null;
count = 0;
}
public int size() {
return count;
}
public boolean isEmpty() {
return count == 0;
}
public void insert(Key key, Value value) {
root = insert(root, key, value);
}
public boolean contain(Key key, Value value) {
return contain(root, key);
}
public Value search(Key key) {
return search(root, key);
}
/**
* 向以node为根的二分搜索树中,插入节点(key,value),使用递归算法 返回插入节点后的二分搜索树的根
*
* @param node
* @param key
* @param value
* @return
*/
private Node insert(Node node, Key key, Value value) {
if (node == null) {
count++;
return new Node(key, value);
}
if (key.compareTo(node.key) == 0)
node.value = value;
else if (key.compareTo(node.key) < 0)
node.left = insert(node.left, key, value);
else
node.right = insert(node.right, key, value);
return node;
}
/**
* 查看以node为根的二分搜索树中是否包含键值为key的节点,使用递归算法 若value不存在 则返回false
*
* @param node
* @param key
* @return
*/
private boolean contain(Node node, Key key) {
if (node == null)
return false;
if (key.compareTo(node.key) == 0)
return true;
else if (key.compareTo(node.key) < 0)
return contain(node.left, key);
else
return contain(node.right, key);
}
/**
* 查看以node为根的二分搜索树中键值为key的节点的value值,使用递归算法
*
* @param node
* @param key
* @return
*/
private Value search(Node node, Key key) {
if (node == null)
return null;
if (key.compareTo(node.key) == 0)
return node.value;
else if (key.compareTo(node.key) < 0)
return search(node.left, key);
else
return search(node.right, key);
}
}