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 :)
The “maximum recursion depth exceeded in comparison” error is raised when you try to execute a function that exceeds Python's built in recursion limit. You can fix this error by rewriting your program to use an iterative approach or by increasing the recursion limit in Python.
Depth-First Search Non-Recursive Function in Python The Python code for the non-recursive depth-first function is similar to the recursive function, except that a Stack Data Structure is necessary to provide the stack functionality inherently present in the recursive function.
12. What happens if the base condition isn't defined in recursive programs? Explanation: The program will run until the system gets out of memory.
Python also accepts function recursion, which means a defined function can call itself. Recursion is a common mathematical and programming concept. It means that a function calls itself. This has the benefit of meaning that you can loop through data to reach a result.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With