2012-02-25 11 views
1

バイナリツリーの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; 
     } 
+1

問題は削除機能にあると思います。これは大丈夫です。 – JProgrammer

+1

'isEmpty'メソッドが正しいです。あなたが 'remove'メソッドを見せてくれれば素晴らしいでしょう。 –

+1

これはあなたの問題の原因ではありませんが、 'return root == null;' – Paul

答えて

0

あなたの削除要素のコードを確認してください。通常、コードは削除ノードの親を見つけ、対応する参照をnullに設定します。最後の要素については、NULL root変数に設定する必要があります。

0

remove(AnyType x, BinaryNode<AnyType> t)の方法では、X要素を持つノードを検索し、removeMinメソッド(2つの子を持つ場合)または左または右の子ノードを使用して、その1つの子で置き換えます。公共の削除方法は次のようなものになります。

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; 
    } 
} 
+0

はまだ動作しませんからそれらを呼び出す。最初に入力した要素を削除しようとすると、isEmptyはまだfalseです。つまり、ルートはまだヌルに設定されていません。 – FranXh

+0

いくつかのデバッグを行い、ツリーに1つの要素しかない場合、ルートとノードが同じ値を持つことを確認しましたか? –

関連する問題