【问题标题】:BST delete method doesn't delete the first node insertedBST 删除方法不会删除插入的第一个节点
【发布时间】:2018-10-11 17:29:43
【问题描述】:

我想不通...我可以毫无问题地插入和排序项目,我可以删除第一个插入之后的节点,但在特殊情况下,我试图删除插入的第一个节点以启动树,它什么也没做。

我不明白为什么会发生这个问题,感谢任何帮助找出逻辑的帮助。

我的代码的淡化版本复制了问题。 https://pastebin.com/hxcqpG1U

这是我的删除方法:

    public void delete(KeyComp key) {
    delete(_root, key);
}

private Node delete(Node root, KeyComp key) {
    //TO-DO: DELETE AN ITEM IN THE TABLE, GIVEN THE KEY

    //empty tree
    if (root == null)
        return root;

    if (key.keyCompareTo(root.data) < 0)
        root.left = delete(root.left, key);
    else if (key.keyCompareTo(root.data) > 0)
        root.right = delete(root.right, key);

    else
    {
        // node with only one child or no child
        if (root.left == null)
            return root.right;
        else if (root.right == null)
            return root.left;

        // node with two children: Get the inorder successor (smallest
        // in the right subtree)
        root.data = getMin(root.right).data;

        // Delete the inorder successor
        root.right = delete(root.right, root.data);
    }

    return root;
}

【问题讨论】:

    标签: java search tree binary binary-search-tree


    【解决方案1】:

    假设您的树没有平衡,插入的第一个节点将是树的根节点。由于您的 delete 方法通过更新树内引用以指向已删除节点周围进行操作,因此除非您还更新指向根节点的指针,否则尝试删除根节点不会做任何事情。

    很难从您提供的代码中看出,但您似乎需要类似以下内容:

    public void delete(KeyComp key) {
        _root = delete(_root, key);
    }
    

    【讨论】:

      猜你喜欢
      • 2021-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-26
      相关资源
      最近更新 更多