2013-10-09 40 views
-1

我設法使用遞歸正確添加節點。添加到二叉搜索樹,返回布爾值

我試圖保持計數時遇到問題,我的遞歸方法在添加節點之前返回false(多次)。似乎它會工作,但最終沒有返回false,但java不喜歡這樣做。

我該如何解決這個問題?

這裏的(僞ISH)代碼:

從集合類:

if(root.add(value)) 
    count++ 
    return true 
return false 

從節點類:

public boolean add(item value) { 
    if(this == value) //check if it already exists 
     return false; 
    } else { 
     if(this.left < value) 
      if(this.left != null) 
       this.left.add(value) 
      else 
       this.left = new Node(value) 
       return true 
     if(this.right > value) 
      if(this.right != null) 
       this.right.add(value) 
      else 
       this.right = new Node(value) 
       return true 
    } 
    return false 
    } 

+0

僞上下的代碼具有我假設在代碼中糾正了一些基本的語法問題。我不明白的是爲什麼你最後還是錯誤的。這意味着當函數調用堆棧被拉時,它肯定會返回多個錯誤。 –

+0

它最後需要返回false,因爲你的方法有返回類型。並且它表示可以在沒有獲得回報的情況下結束自己的方法。 –

+0

@ND_27我相信這就是他的問題所在。 –

回答

2

返回任何遞歸調用返回?

public boolean add(item value) { 
if(this == value) { 
    return false 
} else if(this.left < value) { 
    if(this.left != null) { 
     return this.left.add(value) 
    } else { 
     this.left = new Node(value) 
     return true 
    } 
} else { //if(this.right > value) 
    if(this.right != null) { 
     return this.right.add(value) 
    } else { 
     this.right = new Node(value) 
     return true 
    } 
} 
} 

順便說一句,即使這是僞代碼;如果是(afaict)有點不正確?您正在檢查左側節點是否小於要添加的值,如果是,則將值添加到左側節點中......如果我沒有弄錯,通常會將剩餘的較小值和較高值添加到右側,以便您可能需要交換。 (我假設你已經在代碼中得到了正確的結果)

+0

謝謝,這工作 – opps

0

起初,你確定,問題不是因爲你有錯誤的格式化嗎?這是正確的,因爲你的代碼。正如你所看到的,if (this.right > value)永遠達不到......

public boolean add(item value) { 
    if (this == value) { //check if it already exists 
     return false; 
    } else { 
     if (this.left < value) { 
      if (this.left != null) { 
       this.left.add(value); 

      } else { 
       this.left = new Node(value); 
      } 
     } 
     return true; 
     if (this.right > value) { 
      if (this.right != null) { 
       this.right.add(value); 

      } else { 
       this.right = new Node(value); 
      } 
     } 
     return true 
    } 
    return false 
}