2012-06-08 32 views
1

我有一個節點數據結構定義如下,並不確定find_matching_node方法pythonic或高效。我對發電機並不熟悉,但認爲使用它們可能會有更好的解決方案。有任何想法嗎?Python - 有沒有一種更好/有效的方法來查找樹中的節點?

class HierarchyNode(): 

    def __init__(self, nodeId): 
     self.nodeId = nodeId 
     self.children = {} # opted for dictionary to help reduce lookup time 

    def addOrGetChild(self, childNode): 
     return self.children.setdefault(childNode.nodeId,childNode) 


    def find_matching_node(self, node): 
     ''' 
     look for the node in the immediate children of the current node. 
     if not found recursively look for it in the children nodes until 
     gone through all nodes 
     ''' 
     matching_node = self.children.get(node.nodeId) 
     if matching_node: 
      return matching_node 
     else: 
      for child in self.children.itervalues(): 
       matching_node = child.find_matching_node(node) 
       if matching_node: 
        return matching_node 
      return None 

回答

0

根據您需要在樹上的其他操作,你需要多長時間做這個遞歸,你可以將所有後代節點的存儲在節點上的字典,所以這整個遞歸函數可能是一個字典查找。

+0

這個遞歸不會經常被調用,因爲樹將只有幾個級別的葉子節點。當你說「將所有後代節點存儲在字典中」時,你的意思是直系後代或所有後代。我已經在字典中存儲了直接的孩子,而這個孩子又可以擁有自己的直系孩子的字典。我需要維護每個子小孩的層次結構。希望我試圖正確解釋它。 –

+1

如果你不會經常做這種深入的搜索,那麼我的建議就不好。我的意思是,除了直接孩子的詞典以外,你還可以存儲一個深層兒童的詞典,本質上是遞歸搜索的緩存。 –

+0

謝謝。如果你不介意,如果這個深度搜索必須經常進行,你能否提出你的建議?如果將來發生任何變化,可能會有所幫助。 –

相關問題