使用python中的递归在树中查找节点

时间:2013-08-04 21:15:35

标签: python recursion tree

class Node:
    def __init__(self, tree, data, parent=None):

        self.data = data
        self.parent = parent
        self.children = []   
        self.tree = tree

     def find(self, x):

        if self.data is x:
            return self
        elif self.children:
            for node in self.children:
                return node.find(person)
        else:
            return None

我真的被困了,我似乎无法在我的Node类中创建一个方法,找到一个带有数据x的Node并返回该Node。如果未找到Node,则返回None。

2 个答案:

答案 0 :(得分:1)

您正在搜索儿童中的parent,而您应该搜索x

class Node():
    def __init__(self, tree, data, parent=None):
        self.data = data
        self.parent = parent
        self.children = []   
        self.tree = tree

    def find(self, x):
        if self.data is x: return self
        for node in self.children:
            n = node.find(x)
            if n: return n
        return None


>>> n = Node(None, 1)
>>> n.children = [Node(None, 2), Node(None, 3)]
>>> print n.find(3).data
3

答案 1 :(得分:0)

我认为立即解决的问题是改变这个

    for node in self.children:
        return node.find(person)

到此

    for node in self.children:
        res = node.find(person)
        if res is not None:
            return res