Reputation: 161
I'm set to do a binary tree search like the one here. I have a problem to set the nodes correctly.
The problem: When a new node should be created, the root node seems to be overwriten. First time
Bintree.put(newValue)
is called a new node is created at the Bintree.root. The second time, the root node seems to be overwriten in the functioncall Bintree.put(newValue).
Does these lines below change the root node when it is executed?
node = root
node = node.left # Left is a node below node
node = Node()
The lines below is the code for my program.
# Node for binary tree
class Node():
def __init__(self):
self.data = None
self.left = None
self.right = None
class Bintree:
def __init__(self):
self.root = None
def put(self, newvalue):
'''Sends the new value into the correct position in the Bintree
:param newvalue: The data that's sent to storage'''
self.root = push(self.root, newvalue)
def push(root, value):
# This function puts the value in the correct position in the bintree
# Not to be used by user.
node = root
while node is not None:
if node.data < value:
node = node.left
else:
node = node.right
node = Node()
node.value = value
return node
Upvotes: 0
Views: 580
Reputation: 2526
Yeah you're right I screwed it up a little bit.
class Node(): def init(self): self.data = None self.left = None self.right = Noneclass Bintree: def init(self): self.root = None
def put(self, newvalue): '''Sends the new value into the correct position in the Bintree :param newvalue: The data that's sent to storage''' if self.root is None: self.root = Node() self.root.data = newvalue else: self.push(self.root, newvalue) def push(self, node, value): # This function puts the value in the correct position in the bintree # Not to be used by user. if value < node.data: if node.left is not None: self.push(node.left,value) else: node.left = Node() node.left.data = value else: if node.right is not None: self.push(node.right,value) else: node.right = Node() node.right.data = value
I did it from scratch with recursive. It's simpler. Of course it didn't work because in your first attempt you always set root to none and in the second you only update root all the time (my bad)
Upvotes: 2