我設法使用遞歸正確添加節點。添加到二叉搜索樹,返回布爾值
我試圖保持計數時遇到問題,我的遞歸方法在添加節點之前返回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
}
僞上下的代碼具有我假設在代碼中糾正了一些基本的語法問題。我不明白的是爲什麼你最後還是錯誤的。這意味着當函數調用堆棧被拉時,它肯定會返回多個錯誤。 –
它最後需要返回false,因爲你的方法有返回類型。並且它表示可以在沒有獲得回報的情況下結束自己的方法。 –
@ND_27我相信這就是他的問題所在。 –