バイナリツリーのisEmptyメソッドを自分自身で記述しようとしていますが、問題が発生しています。これは私が使っている方法です。バイナリツリーのメソッドisEmpty
public boolean isEmpty(){
if(root == null) return true;
else return false;
}
要素を1つだけ追加してからこの要素を削除し、isEmptyを呼び出すと、trueになりますが、falseになります。
実装に間違いがありますか?
これは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
'isEmpty'メソッドが正しいです。あなたが 'remove'メソッドを見せてくれれば素晴らしいでしょう。 –
これはあなたの問題の原因ではありませんが、 'return root == null;' – Paul