1

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.

1
  • 8
    Did you mean to write self.node = Node(element,None,None)? Commented Sep 28, 2021 at 9:47

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

Comments

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.