我想寫我自己的二叉樹isEmpty方法,但我有問題。所以這是我正在使用的方法。方法是空的二叉樹問題
public boolean isEmpty(){
if(root == null) return true;
else return false;
}
當我只添加一個元素,然後刪除此元素,並調用的isEmpty,我沒有得到真實的,但假的。
我的實現有一些錯誤嗎?
所以這是remove方法:
/**
* 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;
}
我認爲問題是在刪除功能。這看起來不錯。 – JProgrammer 2012-02-25 21:50:12
'isEmpty'方法是正確的。如果您向我們展示'remove'方法,那將是非常棒的。 – 2012-02-25 21:50:48
這不是你的問題的原因,但你可以'返回root == null;' – Paul 2012-02-25 21:51:17