太恶心了,三种情况理解就好
//! 删除结点
void BinarySearchTreesZH::remove(Node *node)
{
if (node->left != nullptr && node->right != nullptr)//! 把删除度为2 的结点的问题转化为删除
{
node->element = predecessor(node)->element;
remove(predecessor(node));
}
else if (node->left == nullptr && node->right == nullptr) //! 删除度为0的结点
{
if (node->parent == nullptr) //! 若结点是根结点直接置空
{
node = nullptr;
}
if (node == node->parent->left) //!结点时叶结点时的置空
{
node->parent->left = nullptr;
}
if (node == node->parent->right)
{
node->parent->right = nullptr;
}
//!我觉得这里直接全都node = nullptr应该是一样的
}
else
{
//! 删除度为1的结点
if (node->parent == nullptr)//!若结点是根结点,用其子结点替代成为根结点
{
if (node->left != nullptr)
{
root = node->left;
}
else if (node->right != nullptr)
{
root = node->right;
}
}
else if (node == node->parent->left){//! 结点是父结点的左子结点或右子结点时,改动双向指针,和双向链表删除结点操作一样
if (node->left != nullptr)
{
node ->parent->left = node ->left;
node ->left->parent = node ->parent;
}
else if (node->right != nullptr)
{
node ->parent->left = node->left;
node ->left ->parent = node ->parent;
}
}else if (node == node ->parent ->right)
{
if (node->left != nullptr)
{
node ->parent->right = node ->left;
node ->left->parent = node ->parent;
}
else if (node->right != nullptr)
{
node ->parent->right = node->left;
node ->left ->parent = node ->parent;
}
}
}
}