如果你實際上是通過您的跟蹤代碼,就可以很清楚地看到爲什麼它會返回一個不正確的結果。我在下面標明如果沒有樹的第一級的孩子的標籤匹配的代碼路徑(假設左/中/右都是非空):
public TreeNode getNodeReference(String label){
if(left!=null){ // 1: left is not null
if(check(left,label)==true) // 2: no match, proceed to 3
return left;
left.getNodeReference(label); // 3: called, but why? no side effect, no return.
}
if(middle!=null){ // 4
if(check(middle,label)==true) // 5
return middle;
middle.getNodeReference(label); // 6
}
if(right!=null) { // 7
if(check(right,label)==true) // 8
return right;
right.getNodeReference(label); // 9
}
return null; // 10: and finally we're here and we return null
}
從本質上講,你叫孩子。 getNodeReference(標籤),但這就是你所做的一切。你叫它。然後丟棄返回的值並繼續執行,因此,您的搜索實際上不會超出您最初稱爲getNodeReference的節點的第一級。
所以對於初學者來說,這個一般模式是你想要什麼:
if (child != null) {
if (check(child, label))
return child; // match found
TreeNode childResult = child.getNodeReference(label);
if (childResult != null)
return childResult; // match found deeper in tree; this is what you did not do.
}
這就是說,這裏是一個更短的實施(請記住,這是不準確像你有什麼,您的實現也跳過檢查),其getNodeReference首次被實際節點:
public TreeNode getNodeReference (String label) {
if (check(this, label))
return this;
TreeNode childResult = null;
if (left != null)
childResult = left.getNodeReference(label);
if (childResult == null && middle != null)
childResult = middle.getNodeReference(label);
if (childResult == null && right != null)
childResult = right.getNodeReference(label);
return childResult;
}
在一般情況下,你應該坐下來,看看你的代碼很難看,並且一次通過一行一步。通常,當你這樣做時,這樣的問題變得清晰。
希望有所幫助。
您的一般問題是,您遞歸地調用方法,但根據結果不做任何事情。因此,當您調用left.getNodeReference()時,將結果保存在變量中並將其與空值進行比較。如果它非空,則返回結果 - 完成。否則,繼續前進。中間和右邊一樣。 –