I want to create a data structure in Python, but since I'm very C oriented. I need a little bit of help.
In general, I want to create a Node class which will contain the data, a pointer to a sibling, pointers to the children and a pointer to the parent.
this is a way to think of the Node class:
NODE
/ / ... \ \
child_node1 - child_node2 - ... - child_node(N-1) - child_nodeN
What I'm struggling with so far is: I want to overload the '+' operator for the Node class so I can do this:
node1 = Node("data1")
node2 = Node("data2", 3)
node1 = node1 + node2
So basically make the 2 nodes, siblings.
Here's my code:
class Node:
def __init__(self, data = None, numberOfChildren = 0):
'''
Creates a new Node with *numberOfChildren* children.
By default it will be set to 0, meaning it will only create the root of the tree.
No children whatsoever.
'''
self.__sibling_count = 0
self.__parent = Node()
self.__sibling = Node()
self.__data = data
self.__children = []
if numberOfChildren != 0:
'''
The Node has children and we need to initialize them
'''
for i in range(numberOfChildren):
self.__children[i] = Node()
def getParent(self):
return self.__parent
def getData(self):
return self.__data
def getChild(self, i):
'''
Returns the ith child of the current *Node*.
'''
return self.__children[i]
def __add__(self, other):
'''
Overloads the *+* function so that *Node* objects can be added.
The 2 merged *Node* elements will now be siblings.
ex. node1 = Node()
node2 = Node()
node1 = node1 + node2
'''
if self.__sibling_count == 0:
self.__sibling = other
self.__sibling_count += 1
return self
But when I try to add 2 nodes like this:
node1 = Node()
node2 = Node()
node1 = node1 + node2
I get a RuntimeError: maximum recursion depth exceeded
. Why is this happening?