定义:一颗二叉查找树(BST)是一颗二叉树,其中每个结点都含有一个Comparable
的键(以及相关联的值)且每个结点的键都大于其左子树中的任意结点的键而小于右子树的任意结点的键。
每个结点都包括一个键、一个值、一条左链接、一条右链接和一个结点计数器。
基于二叉查找树的符号表:
|
|
floor(Key key):小于等于key的最大键
如果给定的键key小于二叉查找树的根结点键,那么小于等于key的最大键一定在左子树中,如果key大于二叉树的根结点键,可能在右子树中,也可能是根结点键
二叉查找树中max()、min()、floor()方法的实现
|
|
二叉查找树中rank()和select()方法的实现select(排名为k的键)
:如果左子树中的结点数t大于k,我们就继续递归地在左子树中查找排名为k的键;如果t等于k,我们就返回根结点中的键。如果t小于k,我们就(递归地)在右子树中查找排名为(k-t-1)
的键。
|
|
具体实现二叉查找树
命题:在由N个随机键构造的二叉查找树中插入操作和查找未命中中平均所需的比较次数为~2lnN(约1.39lgN)
命题:在一颗二叉查找树中,所有操作在最坏情况下所需的时间和树的高度成正比
Exercise
- Write a test client TestBST.java for use in testing the implementations of
min()
,max()
,floor()
,select()
,rank()
,deleteMin()
,deleteMax()
,andkeys()
that are given in the text - Give nonrecursive implementations of
get()
,put()
,andkeys()
for BST.
solution:NonrecuisiveBST.java
Creative Problems
- Perfect balance. Write a program PerfectBalance.java that inserts a set of keys into an initially empty BST such that the tree produced is equivalent to binary search, in the sense that the sequence of compares done in the search for any key in the BST is the same as the sequence of compares used by binary search for the same set of keys.
Hint: Put the median at the root and recursively build the left and right subtree. - Certification. Write a method isBST() in BST.java that takes a Node as argument and returns true if the argument node is the root of a binary search tree, false otherwise.
- Subtree count check. Write a recursive method isSizeConsistent() in BST.java that takes a Node as argument and returns true if the subtree count field N is consistent in the data structure rooted at that node, false otherwise.
- Select/rank check. Write a method isRankConsistent() in BST.java that checks, for all i from 0 to size() - 1, whether i is equal to rank(select(i)) and, for all keys in the BST, whether key is equal to select(rank(key)).
Web Exercise