繁体   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