I am trying to create a Node class that implements an n-ary tree but I also want to keep track of the parent of each node to trace back to the root.
class Node(object):
def __init__(self, state, children=None, parent=None):
self.state = state
self.children = children or []
self.parent = parent
def add(self, obj):
self.children.append(Node(obj))
Node(obj).parent = self.state
This is what I have been working on. But when I check to see a node's parent, it prints None. In a binary tree, checking if the child was to the left or right makes it easy but for an n-ary tree, I don't really understand how to go about it with explicitly making it the parent.
I am pretty new to Python and coding so I would really appreciate it if anyone could help out! Thank you!
EDIT:
I ran this on the IDE:
>>> n = Node(4)
>>> l = [1,2,3]
>>> for i in l:
n.add_child(i)
>>> n.children.state
Traceback (most recent call last):
File "<pyshell#63>", line 1, in <module>
n.children.state
AttributeError: 'list' object has no attribute 'state'
>>> for child in n.children:
print(child.state)
1
2
3
>>> for child in n.children:
print(child.parent)
None
None
None
>>>