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。
最佳答案
您正在子项中搜索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
关于python - 在python中使用递归查找树中的节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18047634/