簡體   English   中英

刪除Java二進制搜索樹中的方法

[英]Remove method in a Binary Search Tree for Java

所以我的界面說必須照顧以下資格:

/**
 * 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()。

我認為問題來自於你試圖操縱本地節點變量,認為它會影響樹。 例如,看看這部分代碼:

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

當你說node = null你必須考慮到該node不代表真實節點,而是你在調用函數時傳遞的引用的副本。 因此,如果設置node = null ,則只表示本地node變量不再指向樹中的節點,而是指向null。

如果要從樹中刪除節點,則必須先引用父節點,然后使用父節點的引用將子節點設置為null。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM