Java BST节点删除

Java BST节点删除,java,binary-search-tree,Java,Binary Search Tree,我正在读《Java Person中的数据结构和算法分析》(2012),马克·艾伦·韦斯 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. */

我正在读《Java Person中的数据结构和算法分析》(2012),马克·艾伦·韦斯

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 );
    }
如果我希望删除8,则第一步应替换为9

       13
      /  \
     9   14
    / \ 
   6   11
      /  \
     9    12 
然后在11的叶中找到9并将其设置为空

       13
      /  \
     9   14
    / \ 
   6   11
      /  \
     null 12 
所以我不明白为什么会这样

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

else 
     t = null

您提到的else语句是针对节点只有一个子节点的情况执行的(因为针对两个子节点的if-else语句不会计算为true)

因此,您希望在此处分配非空节点,因此:

t = ( t.left != null ) ? t.left : t.right;
这表示如果left不是
null
,则将left分配给
t
,否则将right分配给
t
。这里我们知道我们只有一个孩子,因此只有左或右不为空

因此,如果我们这样做了:

t = null;
那是错误的

t = null;