【问题标题】:Binary Search Tree deletion of target node has two children目标节点的二叉搜索树删除有两个孩子
【发布时间】:2015-04-13 12:20:03
【问题描述】:

这是我的代码,替换是正确的(将目标节点替换为左子树中最大的节点),但是替换后,左右子树都没有了。

这是我的代码:

else if (temp->left != NULL && temp->right != NULL)
    {
        minLeaf = temp->left;
        minLeafMa = temp->left;
        parentRight = parent->right;

        while (minLeaf->right != NULL)
        {
            minLeafMa = minLeaf;
            minLeaf = minLeaf->right;
        }
        if (parent->left == temp)
        {
            parent->left = minLeaf;
            minLeafMa->right = NULL;
        }
        else if (parent->right == temp)
        {
            parent->right = minLeaf;
            minLeafMa->right = NULL;
        }
    }

【问题讨论】:

  • 你还没有问过问题。你只说明了你拥有什么以及它做了什么!
  • 谢谢!问题是,为什么删除后左右子树都消失了,只是替换发生了。

标签: c++ binary-search-tree


【解决方案1】:

删除具有 2 个子节点的节点 x 的正确方法是找到 x 的中序 successorpredecessor,将 x 的值替换为 predecessorsuccessor的值并在其中任何一个上调用 delete(无论您使用哪个)。

您在此处使用predecessor。你在做

parent->left = minLeaf;

将父节点的左侧指向叶节点(predecessor 节点),导致其间的所有节点都消失。相反,你应该做的是

temp->data = minLeaf->data;

并在minLeaf上递归调用delete。

【讨论】:

  • 我的天啊,替换整个节点真是太愚蠢了。谢谢!
  • @YezhenWang 乐于助人! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多