简体   繁体   中英

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.

Right now however, my JUnit tests are failing to remove items correctly. Code as follows:

BSTSet

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

    return false;
}

BSTNode

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:

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. if you called .remove(10). At the end of your ReplacementSubtreeFromChildren method you would have a tree that looked like this [12, 12, 12]. Because you're setting 5, to 12, then 10 to (what was the 5 value) 12.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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