Python - Is there a better/efficient way to find a node in tree?
- by Sej P
I have a node data structure defined as below and was not sure the find_matching_node method is pythonic or efficient. I am not well versed with generators but think there might be better solution using them. Any ideas?
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