簡體   English   中英

不刪除布爾 remove(object o) 方法中的最后一項

[英]Does not remove last item in Boolean remove(object o) method

這刪除了幾乎所有應該刪除的內容,除了最后一項。 這是我提交時得到的:

輸入:[東西,單詞,東西,和,動物園,是的]

----------預期大小:0 BST 實際節點數:1

刪除事物后無效的樹

代碼如下:

@SuppressWarnings("unchecked")
public boolean remove(Object o) {
        Node n = root;
        while (n != null) {
            int comp = n.value.compareTo(o);
            if (comp == 0) {
                size--;
                remove(n);
                return true;
            } else if (comp > 0) {
                n = n.left;
            } else {
                n = n.right;
            }
        }
        return false;
    }

    private void remove(Node root) {
        if (root.left == null && root.right == null) {
            if (root.parent == null) {
                root = null;
            } else {
                if (root.parent.left == root) {
                    root.parent.left = null;
                } else {
                    root.parent.right = null;
                }
            }
        } else if (root.left == null || root.right == null) {
            Node child = root.left; 
            if (root.left == null) {
                child = root.right;
            }
            if (root.parent == null) {   
                root = child;
            } else if (root.parent.left == root) {
                root.parent.left = child;
            } else {
                root.parent.right = child;
            }
            child.parent = root.parent;
        } else {                          
            Node successor = root.right;
            if (successor.left == null) {
                root.value = successor.value;
                root.right = successor.right;
                if (successor.right != null) {
                    successor.right.parent = root;
                }
            } else {
                while (successor.left != null) {
                    successor = successor.left;
                }
                root.value = successor.value;
                successor.parent.left = successor.right;
                if (successor.right != null) {
                    successor.right.parent = successor.parent;
                }
            }
        }
    }

刪除二叉搜索樹中的節點包括以下步驟:

  1. 找到節點

您需要確保您有一個用於搜索的函數,以便找到要刪除的節點。

  1. 處理節點的子樹

如果節點的子節點少於兩個,則可以輕松更改子樹。 如果有子節點,則當前節點將被其子節點替換。 否則,如果要刪除的節點有兩個子節點,則只需將要刪除的節點替換為左子樹的最右側節點或要刪除的元素的右子樹的最左側節點即可。

  1. 確保如果您已用其他節點替換了當前節點,則其他節點將不會作為副本存在。

為了實現這一點,您將需要以下方法: - 搜索 - 找到子樹最左邊/最右邊的節點 - 刪除

您當前的代碼過於復雜。 我會使用原子方法重寫它。

暫無
暫無

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

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