template<class K, class E>
void binarySearchTree<K,E>::erase(const K& theKey)
{// Delete the pair, if any, whose key equals theKey.
// search for node with key theKey
binaryTreeNode<pair<const K, E> > *p = root,
*pp = NULL;
while (p != NULL && p->element.first != theKey)
{// move to a child of p
pp = p;
if (theKey < p->element.first)
p = p->leftChild;
else
p = p->rightChild;
}
if (p == NULL)
return; // no pair with key theKey
// restructure tree
// handle case when p has two children
if (p->leftChild != NULL && p->rightChild != NULL)
{// two children
// convert to zero or one child case
// find largest element in left subtree of p
binaryTreeNode<pair<const K, E> > *s = p->leftChild,
*ps = p; // parent of s
while (s->rightChild != NULL)
{// move to larger element
ps = s;
s = s->rightChild;
}
// move largest from s to p, can't do a simple move
// p->element = s->element as key is const
binaryTreeNode<pair<const K, E> > *q =
new binaryTreeNode<pair<const K, E> >
(s->element, p->leftChild, p->rightChild);
if (pp == NULL)
root = q;
else if (p == pp->leftChild)
pp->leftChild = q;
else
pp->rightChild = q;
//将pp改为新的根节点,p为其要删除的最多只有一个孩子的节点(pp删除p转化为q删除s)
//PS:左子树的最大关键字节点要么没有子树,要么只有一颗子树
if (ps == p) pp = q;
else pp = ps;
delete p;
p = s;
}
// p has at most one child
// save child pointer in c
binaryTreeNode<pair<const K, E> > *c;
if (p->leftChild != NULL)
c = p->leftChild;
else
c = p->rightChild;
// delete p
if (p == root)
root = c;
else
{// is p left or right child of pp?
if (p == pp->leftChild)
pp->leftChild = c;
else pp->rightChild = c;
}
treeSize--;
delete p;
}
二叉搜索树的删除
最新推荐文章于 2024-06-25 18:35:32 发布