2012-07-07 55 views
1

嗨我有此代碼來搜索n-ary樹,但它dosent工作正常,我不知道什麼是錯的 當搜索n4和n5它返回n3 最新錯誤? enter image description here我的搜索非二叉樹(n-ary樹)的方法有什麼問題?

public FamilyNode findNodeByName(FamilyNode nodeName){ 
     if(this.name.equals(nodeName.name)){ 
      // We found a node named nodeName, return it 
      return this; 
     } 
     // That's not me that you are looking for, let's see my kids 

      for(FamilyNode child : this.children){ 
      if(child.findNodeByName(nodeName) != null) 
       return child; 
       // We found what we are looking, just return from here 
      // return child; 

     } 
     // Finished looping over all nodes and did not find any, return null 
     return null; 
    } 

回答

1

的原因是因爲你給回其中一個節點被發現的節點。找到節點後,需要返回此節點,如果發現FamilyNode,則父節點需要返回找到的FamilyNode。檢查found變量做了什麼。

你需要做這樣的事情:

FamilyNode found = child.findNodeByName(nodeName); 
if(found != null) 
    return found; 

整個方法是這樣的:

public FamilyNode findNodeByName(FamilyNode nodeName){ 
    if(this.name.equals(nodeName.name)){ 
     return this; 
    } 
    for(FamilyNode child : this.children){ 
     FamilyNode found = child.findNodeByName(nodeName); 
     if(found != null) 
      return found; 
    } 
    return null; 
} 
+0

吳THX的男人,你是對的THX很多 – Oli 2012-07-07 08:00:27

+0

歡迎你! – 2012-07-07 08:14:38