Reputation: 41
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
I am really stuck, i can't seem to create a method in my Node class that finds a Node with data x and returns that Node. If no Node is found, it will return None.
Upvotes: 3
Views: 8447
Reputation: 117380
you're searching for parent
in children, while you should search for 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
Upvotes: 2
Reputation: 437
I think the immediate fix would be to change this
for node in self.children:
return node.find(person)
To this
for node in self.children:
res = node.find(person)
if res is not None:
return res
Upvotes: 0