簡體   English   中英

二進制搜索樹查找最大節點並將其刪除(通用類)

[英]Binary Search Tree find max node and delete it (Generic classes)

如標題所示,我當前正在嘗試查找BST的最大節點,並且想要刪除它。 我有一些方法可以從我的“算法”書中找到findMax節點和刪除節點,但是我無法弄清楚如何在主要方法中使用它們。 我有一種方法,可以通過輸入數字來插入節點,例如8,它將按順序打印樹:4,2,6,1,3,5,7,其中4是根。 我希望能夠找到最后一個節點並將其刪除。 到目前為止,我有這些方法:

public BinaryNode remove(AnyType x, BinaryNode<AnyType> t)
{
    if(t == null)
        return t;

    int compareResult = x.compareTo(t.element);

    if(compareResult < 0 )
        t.left = remove(x, t.left);
    else if(compareResult > 0)
        t.right = remove(x, t.right);
    else if(t.left != null && t.right != null)
    {
        t.element = (AnyType) findMax(t.right).element;
        t.right = remove(t.element, t.right);
    }
    else
        t = (t.left != null) ? t.left : t.right;
    return t;
}

public BinaryNode<AnyType> remove(AnyType x)
{
    return root = remove(x, root);
}

public BinaryNode<AnyType> findMax(BinaryNode<AnyType> t)
{
    if(t != null)
        while(t.right != null)
            t = t.right;
    return t;
}

我的主要方法如下:

public static void main(String[] args)
{
    CompleteBinarySearchTree<Integer> bst = new CompleteBinarySearchTree<>();
    BinaryNode<Integer> tree = bst.createBinarySearchTree(bst.insertNodes(8));
    bst.printLevelOrderedBST(tree);
}

我希望能夠自由插入任何節點,並且樹仍然應該能夠刪除最大節點。 我不知道如何在findMax()上調用remove()方法。 我當然可以調用remove(7,tree),它將刪除7,但這不是我想要的。 任何幫助深表感謝。

刪除max節點的關鍵是必須跟蹤其父節點,因此可以更新父節點的right指針(將其設置為null )。 您還必須處理所傳遞的節點沒有合適的子節點的情況,其中該節點本身是最大的節點。

下面的代碼顯示了基本思想。 未經測試,但應該接近。

// removes the largest node in the binary tree with root at t.
// returns the new root.
public BinaryNode<AnyType> removeMax(BinaryNode<AnyType> t)
{
    if (t == null) return null;
    if (t.right == null) {
        // the node passed in is the largest.
        return t.left;
    }

    // traverse the right branch to the last node,
    // keeping track of the previous node so you can correctly set its
    // right pointer to null.
    BinaryNode<AnyType> parent = t;
    BinaryNode<AnyType> child = parent.right;
    while (child.right != null) {
        parent = child;
        child = child.right;
    }
    parent.right = null;
    return t;
}

暫無
暫無

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

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