'Making a tree form a Dictionary of lists
I'm a new programmer. I am trying to make a Tree from a dictionary that contains all the links between the nodes. Here is an example
{ 'A': ['B', 'C'],
'B': ['A', 'D'],
'C': ['B', 'A']
}
Edit: I know it looks like a dictionary for a graph. If a 'son' is somewhere in the tree it should not be added.
I need to find, knowing the generation, all the 'sons' of that generation.
I have tried writing from scratch a class (first time I write a class), but it does not work.
class Tree:
def __init__(self, data):
self.data = data
self.children = []
self.parent = None
def add_child(self, child):
child.parent = self
self.children.append(child)
def maketree(self, dictionary):
for node in dictionary[self.data]:
if node != self.parent:
self.add_child(TreeNode(node))
if self.children != []:
for child in self.children:
child.maketree(dictionary)
It says, referring to the last line of code
[Previous line repeated 993 more times] RecursionError: maximum recursion depth exceeded
If you have other questions or any doubt or clarification please ask
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|