2012-02-25 96 views
1

我想寫我自己的二叉樹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; 
     } 
+1

我認爲問題是在刪除功能。這看起來不錯。 – JProgrammer 2012-02-25 21:50:12

+1

'isEmpty'方法是正確的。如果您向我們展示'remove'方法,那將是非常棒的。 – 2012-02-25 21:50:48

+1

這不是你的問題的原因,但你可以'返回root == null;' – Paul 2012-02-25 21:51:17

回答

0

檢查remove元素的代碼。通常比代碼找出刪除節點的父節點並將其設置爲空對應的引用。對於最後一個元素,它必須設置爲null root變量。

0

您的remove(AnyType x, BinaryNode<AnyType> t)方法使用X元素搜索節點,並使用removeMin方法(如果它有2個孩子)或使用左側或右側子節點,用其中一個子元素替換它。你的公開刪除方法可能是這樣的:

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,這意味着根目錄尚未設置爲null。 – FranXh 2012-02-25 23:07:52

+0

你有沒有做過一些調試,並檢查過,當你的樹只有1個元素時,根和節點具有相同的值? – 2012-02-25 23:11:09