【问题标题】:BST node deletionBST 节点删除
【发布时间】:2016-06-26 09:43:42
【问题描述】:

我正在阅读“Java-Person (2012),Mark Allen Weiss 中的数据结构和算法分析”一书。

BST中删除节点的代码

  /**
     * Internal method to remove from a subtree.
     * @param x the item to remove.
     * @param t the node that roots the subtree.
     * @return the new root of the subtree.
     */
    private BinaryNode<AnyType> remove( AnyType x, BinaryNode<AnyType> t )
    {
        if( t == null )
            return t;   // Item not found; do nothing

        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 ) // Two children
        {
            t.element = findMin( t.right ).element;
            t.right = remove( t.element, t.right );
        }
        else
            t = ( t.left != null ) ? t.left : t.right;
        return t;
    }
    /**
     * Internal method to find the smallest item in a subtree.
     * @param t the node that roots the subtree.
     * @return node containing the smallest item.
     */
    private BinaryNode<AnyType> findMin( BinaryNode<AnyType> t )
    {
        if( t == null )
            return null;
        else if( t.left == null )
            return t;
        return findMin( t.left );
    }

我了解删除节点的一​​般方法是将删除节点的值替换为右侧的最小值。

我的问题是什么是“其他声明”? 例如,

       13
      /  \
     8   14
    / \ 
   6   11
      /  \
     9    12

如果我想去掉8,第一步应该换成9

       13
      /  \
     9   14
    / \ 
   6   11
      /  \
     9    12 

然后在11的叶子中找到9并将其设置为null,

       13
      /  \
     9   14
    / \ 
   6   11
      /  \
     null 12 

所以我不明白为什么会这样

else
     t = ( t.left != null ) ? t.left : t.right;

而不是

else 
     t = null

【问题讨论】:

    标签: java binary-search-tree


    【解决方案1】:

    您提到的 else 语句是针对节点只有一个孩子的情况执行的(因为用于两个孩子情况的 if else 语句不会被评估为真)。

    结果,这里你要分配非Null节点,所以你这样做:

    t = ( t.left != null ) ? t.left : t.right;
    

    如果left不是null,则将left分配给t,否则将right分配给t。这里我们知道我们只有一个孩子,因此只有 left 或 right 不会为空。

    如果我们这样做了:

    t = null;
    

    那是错误的。

    【讨论】:

      猜你喜欢
      • 2021-04-06
      • 2014-05-26
      • 2016-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-23
      相关资源
      最近更新 更多