Python - Is there a better/efficient way to find a node in tree?

Posted by Sej P on Stack Overflow See other posts from Stack Overflow or by Sej P
Published on 2012-06-08T21:36:18Z Indexed on 2012/06/08 22:40 UTC
Read the original article Hit count: 208

Filed under:
|
|
|

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

© Stack Overflow or respective owner

Related posts about python

Related posts about tree