简体   繁体   English

无法删除二叉搜索树中的根节点

[英]Can't remove root node in Binary Search Tree

I'm trying to remove the root of my binary search tree so I can update it's value, but this method can't do it.我试图删除我的二叉搜索树的根,以便我可以更新它的值,但这种方法无法做到这一点。 My idea is to remove the root, and then insert it again in the binary search tree but with another value.我的想法是删除根,然后将其再次插入二叉搜索树中,但使用另一个值。 It works with every Node in the tree, but not the root cause I cannot delete it.它适用于树中的每个节点,但不是我无法删除它的根本原因。 Anyone knows why this happens?任何人都知道为什么会这样? Thanks.谢谢。

public V remove(K key) {
    Node node = remove(key, root);
    return node.value;
}

private Node remove(K key, Node current) {
    if (current == null) { 
        return null;
    }
    if (current.key.equals(key)) { 
        
        if (current.left == null && current.right == null) {
            return null;
        } 
        else if (current.left == null && current.right != null) {
            return current.right;
        } else if (current.left != null && current.right == null) {
            return current.left;
        } else {
            Node plowest = current.right;
            Node parent = current;
            while (plowest.left != null) {
                parent = plowest;
                plowest = plowest.left;
            }
            plowest.left = current.left;
            if (plowest != current.right) {
                parent.left = plowest.right;
                plowest.right = current.right;
            }
            return plowest;
        }
    }
    if (key.compareTo(current.key) < 0) { // Subarbre esquerra
        current.left = remove(key, current.left);                                   
    } else {// Subarbre dret
        current.right = remove(key, current.right);
    }
    return current;
}

And this is the main code where I call the method to delete any Node, in this case I would like to delete the root.这是我调用删除任何节点的方法的主要代码,在这种情况下我想删除根。

public static void main(String[] args) {

    BSTMapping<String, Integer> arbre = new BSTMapping();
    arbre.put("G", 4);
    arbre.put("A", 1);
    arbre.put("C", 2);

    arbre.remove("G");

    Iterator it = arbre.iterator();
    while (it.hasNext()) {
        BSTMapping.Pair p = (BSTMapping.Pair) it.next();
        System.out.println(p.getKey() + " - " + p.getValue());
    }

     
}

When removing root, remove(K key, Node current) never reaches the bottom where it would assign a node to current.left or current.right .删除根时, remove(K key, Node current)永远不会到达底部,它将节点分配给current.leftcurrent.right You can address this in remove(key) by assigning directly to the root variable when appropriate.您可以通过在适当的时候直接分配给root变量来在remove(key)中解决这个问题。

public V remove(K key) {
    Node node = remove(key, root);
    if (root.key.equals(key)) {
       root=node;
    }
    return node.value;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM