简体   繁体   English

从Java中的二进制搜索树中删除节点?

[英]Removing a node from a binary search tree in Java?

I've been given a binary search tree, and as part of what I've been tasked to do, I need to implement a remove() method on both my set and node class. 我已经得到了一个二进制搜索树,作为任务的一部分,我需要在set和node类上都实现remove()方法。

Right now however, my JUnit tests are failing to remove items correctly. 但是,现在,我的JUnit测试无法正确删除项目。 Code as follows: 代码如下:

BSTSet BSTSet

public boolean remove(E item) {     
    if (this.contains(item)) {
        this.root.remove(item);
        this.count--;
        return true;
    }   

    return false;
}

BSTNode BST节点

public BSTNode<E>remove(E item) {
    if (item.equals(this.value)) {
        return this.replacementSubtreeFromChildren(this.left, this.right);
    }

    if (item.compareTo(this.value) < 0) {
        this.left = this.left.remove(item);
    } else {
        this.right = this.right.remove(item);
    }

    // there was no need to replace the receiver node
    return this;  
}

where replacementSubtreeFromChildren is: 其中replacementSubtreeFromChildren是:

private BSTNode<E> replacementSubtreeFromChildren(BSTNode<E> left, BSTNode<E> right) {
    if (left == null && right == null) {
        return null;
    }

    if (left != null && right == null) {
        return left;
    }

    if (right != null && left == null) {
        return right;
    }

    this.getLeftmostNode().value = this.right.getLeftmostNode().value;      
    this.value = this.getLeftmostNode().value;      
    return this;
}

I'd prefer an indirect answer if possible. 如果可能,我希望使用间接答案。 I'd like to try and figure this out myself. 我想尝试自己解决这个问题。 Can anyone provide some pointers as to what's going wrong here? 任何人都可以提供一些有关这里出了什么问题的指示吗?

Wouldn't say this is an answer but I can't comment with my rep. 不会说这是一个答案,但我无法对自己的代表发表评论。 Posting how the node is implemented would help. 发布节点的实现方式将有所帮助。

if your tree is being visualized as an array [10, 5, 12] such that 5, is the left node of 10, and 12 is the right node. 如果您的树被可视化为数组[10,5,12],使得5是10的左节点,而12是右节点。 if you called .remove(10). 如果您调用.remove(10)。 At the end of your ReplacementSubtreeFromChildren method you would have a tree that looked like this [12, 12, 12]. 在ReplacementSubtreeFromChildren方法的最后,您将有一棵看起来像这样的树[12,12,12]。 Because you're setting 5, to 12, then 10 to (what was the 5 value) 12. 因为您将5设置为12,然后将10设置为(5的值)12。

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

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