二叉查找树是每一个几点都满足左孩子小于根,右孩子大于根的数。为查找而生。
1.创建
-
bool Insert(BSTNode<K,V>*& root,const K& key,const V& v)
-
{
-
if(root == NULL)
-
{
-
root = new Node(key,v);
-
return true;
-
}
-
else
-
{
-
if(key < root->_key)
-
{
-
Insert(root->_left,key,v);
-
}
-
if(key > root->_key)
-
{
-
Insert(root->_right,key,v);
-
}
-
else
-
{
-
return false;
-
}
-
}
-
}
2.查找(递归、非递归)
-
bool Find_R(BSTNode<K,V>*& root,const K& key)//递归实现
-
{
-
if(root == NULL)
-
{
-
return false;
-
}
-
else
-
{
-
if(key == root->_key)
-
{
-
return true;
-
}
-
else if(key > root->_key)
-
{
-
Find_R(root->_right,key);
-
}
-
else
-
{
-
Find_R(root->_left,key);
-
}
-
}
-
}
-
bool Find(BSTNode<K,V>*& root,const K& key)//非递归实现
-
{
-
if(root == NULL)
-
{
-
return false;
-
}
-
Node *cur = root;
-
while(cur)
-
{
-
if(key == cur->_key)
-
{
-
return true;
-
}
-
if(key < cur->_key)
-
{
-
cur = cur->_left;
-
}
-
else
-
{
-
cur = cur->_right;
-
}
-
}
-
return false;
-
}
3.删除(递归、非递归)
4.摧毁
-
void Destroy(BSTNode<K,V>* root)
-
{
-
if(root == NULL)
-
{
-
return;
-
}
-
Destroy(root->_left);
-
Destroy(root->_right);
-
if(root->_left == NULL&&root->_right == NULL)
-
{
-
delete root;
-
}
-
}
阅读(1437) | 评论(2) | 转发(0) |