0

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 

1 Answer 1

2

Yeah you're right I screwed it up a little bit.

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''' 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)

Sign up to request clarification or add additional context in comments.

1 Comment

Changed the thing you commented. Put if I try the following: bintree = Bintree() bintree.put(12) bintree.put(13) I get error when executing bintree.put(13) that node exists, but node.data does not have any value in the loop in push.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.