2015-11-01 55 views
0

我有一個簡單的數字樹定義如下:查找最長的單詞在數字樹遞歸

class DTN { 
    public: 
    DTN() : 
     is_word(false), word_to_here(""), children() 
    {} 
    DTN (bool iw, std::string wth) : 
     is_word(iw), word_to_here(wth), children() 
    {} 
    bool      is_word; 
    std::string    word_to_here; 
    Map<char,DTN> children; 
}; 

我有問題要定義一個名爲longest_word功能(常量DTN & DTN),這是假設返回最長的單詞與迭代和遞歸數字樹,顯示如下:

std::string longest_word (const DTN& dtn) { 
    std::string lw = dtn.word_to_here; 
    for(auto s:dtn.children){ 
     if(s.second.is_word && lw.length()<s.second.word_to_here.length()){ 
      lw = longest_word(s.second); 
     } 
     longest_word(s.second); 
    } 
    return lw; 
} 

假設我們有一個數字樹DTN三個字:(賭注,食蟻獸,anthebellum),並調用longest_word(DTN)將給我一個空的字符串「」,而不是「anthebellum」。有人能指出我在longest_word函數中做錯了什麼嗎?隨着實際的代碼將不勝感激,因爲我的英文不好,代碼更容易理解。提前致謝。

+0

這看起來不夠 - 兒童型? NTN與DTN? – mksteve

+0

我很抱歉,我在這裏把錯誤的課,我正在更新正確的。 – Saoish

回答

1

longest_word的算法是完全錯誤的。你應該檢查所有的孩子longest_words並返回一個更長的。在兒童循環完成之前,您無法返回。請注意,您的算法將始終返回第一個孩子。我甚至不明白你爲什麼要檢查一個完整的單詞......

我可以嘗試寫出正確的代碼,但我覺得它對你沒有用。我的建議是回到最簡單的算法,如在整數列表中查找最大數量。