Reputation: 622
I'm trying to learn python with some data-structure. I'm trying to create a binary tree.
So I've created a node like:
class Node(object):
def __init__(self,value,left,right):
self.value = value
self.left = left
self.right = right
Then I've created a tree like:
class Tree(object):
def __init__(self):
self.node = None
def insert(self,node,element):
if node == None:
node = Node(element,None,None)
return
elif element <= node.value:
self.insert(node.left, element)
else:
self.insert(node.right, element)
When I'm trying to insert element
to the tree, it doesn't work. There is a stack call for that insert
and the node==None
is hitting and new Node
is being created. But the Tree
is not updating.
Upvotes: 1
Views: 127
Reputation: 2408
The line
node = Node(element,None,None)
will create a method local variable, which is only visible in the scope of that method. Thus it will not affect the Tree
instance in any way. To create an instance variable, use
self.node = Node(element,None,None)
Upvotes: 3