【发布时间】: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
【问题讨论】: