2012-03-07 92 views
1

請在下面找到我的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)。上面的實現不按預期工作。你能否指出我的代碼不符合邏輯建議的地方?

回答

3

菜鳥,我可能會建議使用循環經典(實現而不是增強的for循環現在正在使用),它可以整合你的止損條件好一點,是這樣的:因此,一旦

protected boolean DFS(String key) { 
    boolean found = false; 

    for(int i = 0; i < leafs.size() && !found; i++) { 
     Tree<T> child = leafs.get(i); 

     if(child.head.equals(key)) 
      found = true; 
     else 
      found = child.DFS(key); 
    } 

    return found; 
} 

爲您缶nd條件被擊中,'找到'成爲真,你的循環停止。

你可能已經忘記了遞歸的「found = child.DFS(key)」部分,在這裏你需要記住遞歸調用的結果,因此鏈上的所有for循環都會被打破爲一旦你回來。

希望有所幫助。

+0

感謝您的回覆。我將你的函數插入到我的程序中,但它仍然不起作用。根據它顯然應該的邏輯。控件沒有輸入if(child.head.equals(key))條件。關鍵肯定在樹上。它會是一個鑄造錯誤? – 2012-03-08 00:09:36

+0

解決!是的,Generic和String之間需要一個鑄造聲明。 – 2012-03-08 00:12:55

+0

注意:Riyad指出的訣竅是循環必須在每次迭代中檢查是否找到了正確的節點! – Jochen 2012-03-08 00:13:40

1

選項A(尼斯):該函數返回一個值,當找到該節點時,返回一個不同的值,如果找不到節點。當您調用方法時,如果得到found值,則停止循環並返回found值。

選項B(醜):找到了,如果是一個異常(更好,如果它是你自己的實現)。不要忘記抓住它。

選項C(Uglier):與全局(靜態)變量相同。

更新1:

它看起來像你的方法應該可以立即運行,可以檢查(System.out.println)如果你的價值是迄今發現的?

在更個人的意見,我會找到

protected boolean DFS(String anaphorKey) { 
    for(Tree<T> child : leafs) { 
    if(child.head.equals(anaphorKey)) 
     return true; 
    if(child.DFS(anaphorKey)) // No need to store value. No need to check == true (it is implicit) 
     return true;    // If we are in this line the value was found, always return true 
    System.out.println(child.head);  
    //System.out.println("anaphorKey: "+anaphorKey); 
    } 
    return false; // If the method did not exit previously it was because the value was not found, so in this line always return false 
} 

更具可讀性(但它應該工作完全爲您的實現)

+0

請參閱上面的Edit1;需要指導。 – 2012-03-07 23:51:28

+0

是的,它找到節點時停止搜索。 [利雅德]提出的建議確實也通過父母追溯到找到的節點;根據我對你的建議的理解,我實現的那個不會追溯到搜索節點的父母身上。 – 2012-03-08 00:24:09