我试图为二叉树编写isEmpty方法,但我遇到了问题。这就是我所用的方法。
public boolean isEmpty(){
if(root == null) return true;
else return false;
}
当我只添加一个元素,然后删除这个元素,并调用isEmpty时,我不会得到true,而是false。
我的执行有什么问题吗?
这就是删除方法:
/**
* Internal method to remove from a subtree.
* @param x the item to remove.
* @param t the node that roots the tree.
* @return the new root.
* @throws ItemNotFoundException if x is not found.
*/
protected BinaryNode<AnyType> remove( AnyType x, BinaryNode<AnyType> t )
{
if( t == null )
throw new ItemNotFoundException( x.toString( ) );
if( x.compareTo( t.element ) < 0 )
t.left = remove( x, t.left );
else if( x.compareTo( t.element ) > 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 = removeMin( t.right );
}
else
t = ( t.left != null ) ? t.left : t.right;
return t;
}
这是remove方法使用的removeMin方法:
/**
* Internal method to remove minimum item from a subtree.
* @param t the node that roots the tree.
* @return the new root.
* @throws ItemNotFoundException if t is empty.
*/
protected BinaryNode<AnyType> removeMin( BinaryNode<AnyType> t )
{
if( t == null )
throw new ItemNotFoundException( );
else if( t.left != null )
{
t.left = removeMin( t.left );
return t;
}
else
return t.right;
}
发布于 2012-02-25 21:52:25
检查删除元素代码。通常比代码查找删除节点的父节点并将其设置为空对应的引用。对于最后一个元素,它必须设置为空root
变量。
发布于 2012-02-25 22:28:16
remove(AnyType x, BinaryNode<AnyType> t)
方法使用X元素搜索节点,并使用removeMin
方法(如果它有两个子节点)或左或右子节点替换它的一个子节点。您的公共删除方法可能如下所示:
public boolean remove(AnyType x) {
try {
BinaryNode<AnyType> node = remove(x, root);
if (node != null) {
node = null;
return true;
}
return fal
} catch (Exception e) {
//do something with the exception
return false;
}
}
https://stackoverflow.com/questions/9448364
复制相似问题