树中的每一个节点包含特定人员的数据。人名是查找关键字,是可在图中看到的唯一的数据项。下面的c++语句描述了树节点中的数据:
#include<string>
using namespace std;
typedef string keyType;
class KeyItem
{
public:
KeyItem();
KeyItem(const KeyType &keyValue)
:searchKey(keyValue)
{}
KeyType getKey()const
{
return searchKey;
}
private:
KeyItem searchKey;
};
class Person :public KeyItem
{
public:
Person();
Person(const string &name,
const string &id,
const string &phone)
:KeyItem(name),idNum(id)
,phoneNumber(phone)
{}
private:
string idNum;
string phoneNumber;
};
因为二叉查找树的本质上是递归的,所以很自然为树的操作设计递归算法。假设要在图1的二叉树中查找Ellen的记录。Jane在树的根节点中,所以若树中存在Ellen的记录,则必然在Jane的左子树中,因为按字母顺序,查找关键字Ellen在查找关键字Jane之前。有递归的定义知,Jane的左子树也是二叉树,因此可用完全相同的策略,在子树中查找ELlen。Bob是这个二叉查找树的根,因为关键字Ellen大于关键字Bob,所以Ellen的记录必然在Bob的右子树中。Bob的右子树也是二叉查找树,而Ellen正好在该树的叶节点中。这样就找到了Ellen的记录。
图1