####这篇接上一篇二叉搜索树,上篇分析完了删除的所有情况,今天就将其用代码实现出来
####一、删除节点
bool Rmove(const K& key)
{
Node* cur = _root;
Node* parent = cur;
//先去找要删除的位置
while (cur)
{
if (key < cur->_key)
{
parent = cur;
cur = cur->_left;
}
else if (key>cur->_key)
{
parent = cur;
cur = cur->_right;
}
else//找到要删的位置了
{
Node* del = cur;
//判断情况
//1、左为空/右为空
//左为空
if (cur->_left == NULL)
{
if (cur == parent->_left)
{
parent->_left = cur->_right;
}
else if (cur == parent->_right)
{
parent->_right = cur->_right;
}
//特殊情况删除的是根
else if (cur==_root)
{
_root = cur->_right;
}
}
//右为空
else if (cur->_right == NULL)
{
if (cur == parent->_left)
{
parent->_left = cur->_left;
}
else if (cur == parent->_right)
{
parent->_right = cur->_left;
}
//特殊情况删除的是根
else if (cur == _root)
{
_root = cur->_left;
}
}
//左右都不为空
else
{
//替代法
//先找右子树的最小值
Node* prev = cur;
Node* subRight = cur->_right;
while (subRight->_left)
{
prev = subRight;//记录一下前节点
subRight = subRight->_left;
}
//找到替换值了subRight
//如果subRight没有左子树
if (cur->_right == subRight)
{
cur->_right = subRight->_right;
}
else
{
cur->_key = subRight->_key;
}
del = subRight;
}
delete del;
return true;
}
}
}
####二、查找
Node* Find(const K&key)
{
assert(_root);
Node* cur = _root;
while (cur)
{
if (key < cur->_key)
{
cur = cur->_left;
}
else if (key>cur->_key)
{
cur = cur->_right;
}
else
{
return cur;
}
}
cout << "没找到" << endl;
return 0;
}