删除Java二进制搜索树中的方法

时间:2014-02-24 20:28:08

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

所以我的界面说必须照顾以下资格:

/**
 * Remove the data element from the tree.
 * 
 * In the case that a node you want to remove has two children
 * replace it with the successor. If the data is null throw 
 * IllegalArgumentException.
 * 
 * @param data The data you want to remove.
 *            
 * @return The data that was removed from the tree. Return null if
 *         the data doesn't exist.
 */
public T remove(T data);

这是我到目前为止已完成的一些额外调试:

public T remove(T data) {
    if (data == null) {
        throw new IllegalArgumentException();
    }
    return removeHelper(data, root);
}

    public T removeHelper(T data, Node<T> node) {
    System.out.println("DATA: " + data);
    System.out.println("NODE: " + node);
    System.out.println(); 

    if (node == null) {
        System.out.println("I should be here last: " + data);
        return data;
    } else if (data.compareTo(node.getData()) < 0) {
        System.out.println("im here");
        removeHelper(data, node.getLeft());
    } else if (data.compareTo(node.getData()) > 0) {
        removeHelper(data, node.getRight());
    } else {
        System.out.println("im here again");
        if (node.getLeft() != null && node.getRight() != null) {
            node.setData(minFromRight(node.getRight()).getData());
            removeHelper(minFromRight(node.getRight()).getData(), node.getRight());
        } else if (node.getLeft() != null) {
            node = node.getLeft();
        } else if (node.getRight() != null) {
            node = node.getRight();
        } else {
            node = null;
            removeHelper(data, node);
        }
    }
    return null;
}

private Node<T> minFromRight(Node<T> toTraverse) {
    if (toTraverse.getLeft() == null) {
        return toTraverse;
    } else if (toTraverse.getLeft() != null) {
        minFromRight(toTraverse.getLeft());
    }
    return null;
}

我已经开始测试叶子节点的情况但它们不起作用。难道我做错了什么? BST的所有其他功能都能正常工作并经过彻底测试。我只需要得到这个darn remove()。

1 个答案:

答案 0 :(得分:2)

我认为问题来自于你正试图操纵本地节点变量,认为它会影响树。例如,看一下代码的这一部分:

} else {
     node = null;
     removeHelper(data, node);
}

当您说node = null时,您必须考虑到node不代表真实节点,而是您在调用函数时传递的引用的副本。因此,如果您设置node = null,那么您只是说本地node变量不再指向树中的节点,而是指向null。

如果要从树中删除节点,则必须先引用父节点,然后使用父节点的引用将子节点设置为null。