3
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。

4

2 回答 2

2

您正在寻找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
于 2013-08-04T21:22:07.880 回答
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
于 2013-08-04T21:21:55.467 回答