12

I'm making a binary tree in Python 3.5.0 and I'm making the insert function for it. But I'm running in a bit of a problem when I call tree_insert inside itself it gives me this error:

  File "D:/MadeUpPath/BinaryTree.py", line 10, in tree_insert
    tree_insert(data, self.left)
NameError: name 'tree_insert' is not defined
class BinaryTree():
    def __init__(self, data):
        self.left = None
        self.right = None
        self.data = data

    def tree_insert(self, data):
        if (data < self.data):
            if (self.left != None):
                tree_insert(data, self.left)
            else:
                self.left = BinaryTree(data)
        else:
            if (self.right != None):
                tree_insert(data, self.right)
            else:
                self.right = BinaryTree(data)

Upon testing further I found out that recursive functions simply don't work. I tried the following code to be sure but gave me the same error:

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n - 1)
  File "D:/MadeUpPath/BinaryTree.py", line 23, in factorial
    return n * factorial(n - 1)
NameError: name 'factorial' is not defined

If anyone can point me in the right direction it would be much appreciated :)

1 Answer 1

27

tree_insert() is an instance method, call it via self.tree_insert():

class BinaryTree():
    def __init__(self, data):
        self.left = None
        self.right = None
        self.data = data

    def tree_insert(self, data):
        if (data < self.data):
            if (self.left != None):
                self.tree_insert(data, self.left)
            else:
                self.left = BinaryTree(data)
        else:
            if (self.right != None):
                self.tree_insert(data, self.right)
            else:
                self.right = BinaryTree(data)
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.