請在下面找到我的DFS實現。DFS樹遍歷函數修改
protected void DFS(String search) {
for(Tree<T> child : leafs) {
if(child.value.equals(search))
return;
else
child.DFS(search);
System.out.println(child.value);
}
}
目標是停止遍歷查找其值在變量搜索中的節點。但是,上述函數繼續遍歷樹,甚至超出了聲明的搜索節點。有人可以幫我修改上述功能嗎?
謝謝。
編輯1
protected boolean DFS(String anaphorKey) {
boolean found = false;
for(Tree<T> child : leafs) {
if(child.head.equals(anaphorKey))
return true;
found = child.DFS(anaphorKey);
if(found == true)
break;
System.out.println(child.head);
//System.out.println("anaphorKey: "+anaphorKey);
}
return found;
}
試圖實現給定答案的建議(@ SJuan76)。上面的實現不按預期工作。你能否指出我的代碼不符合邏輯建議的地方?
感謝您的回覆。我將你的函數插入到我的程序中,但它仍然不起作用。根據它顯然應該的邏輯。控件沒有輸入if(child.head.equals(key))條件。關鍵肯定在樹上。它會是一個鑄造錯誤? – 2012-03-08 00:09:36
解決!是的,Generic和String之間需要一個鑄造聲明。 – 2012-03-08 00:12:55
注意:Riyad指出的訣竅是循環必須在每次迭代中檢查是否找到了正確的節點! – Jochen 2012-03-08 00:13:40