Reputation: 51155
I am creating a tree in python, and I had a method to find a path from the parent to the root node of the tree. That is as follows:
def get_sub_net(self, index):
node = self.nodes[index]
sub_net = []
sub_net.append(node)
while node.parent is not None:
node = node.parent
sub_net.append(node)
return sub_net[::-1]
Now I am trying to allow for each node to have multiple parents, and I am running into trouble.
def sub_net(self, index):
node = self.nodes[index]
sub_net = []
if node.parents == None:
return sub_net
else:
sub_net += node.parents
for i in node.parents:
while i is not None:
sub_net += i.parents
node = i
break
return sub_net[::-1]
@Noreddine-Kessa pointed out that this would be a graph, and not a tree, which is correct. However, I also solved my own problem, the solution I used i
def recursive_sub_net(self, node):
sub_net = []
sub_net.append(node)
if node.parents is not None:
for i in node.parents:
sub_net += self.recursive_sub_net(i)
return sub_net
Upvotes: 1
Views: 1812
Reputation: 46
By definition, every node in a tree has a single parent (and can have many ancestors), if you need to use a network of nodes (not tree) then you should use a graph.
Upvotes: 2