Reputation: 169
I am trying to build tree from scratch but getting Maximum recursion error. Kindly, Help me to find the error.
First i created a node and with make_node function, i am trying to build tree. then with the help of inorder function i am trying to print the data in the node.
class node:
def __init__(self,data):
self.data = data
self.left = None;
self.right = None;
class tree:
def __init__(self):
self.start = None;
def make_node(self,data):
if(self.start==None):
self.start = node(data)
print(self.start.data)
return
#temp = self.start
if(self.start.data<data):
if(self.start.left == None):
print(self.start.left.data)
self.start.left = node(data)
else:
self.start.left(self.make_node(data))
elif(self.start.data>=data):
print(self.start.right.data)
if(self.start.right == None):
self.start.right = node(data)
else:
self.start.right(self.make_node(data))
def inorder(self):
#temp2 = self.start
if(self.start==None):
return
self.start = self.start
self.inorder(self.start.left)
print(self.start.data)
self.inoder(self.start.right)
BST = tree()
BST.make_node(2)
BST.make_node(3)
BST.make_node(4)
BST.make_node(5)
BST.inorder()
Can you guys help me to find my mistakes. Thanks in advance.
Upvotes: 1
Views: 56
Reputation: 1654
Errors I have found:
1. You can't call the function like this: self.start.left(self.make_node(data)). As self refers to the object of the tree, not an object of the node. For referencing Node object you can pass as a parameter. So, I have rectified this error everywhere in your code.
2. Also, you have used inequalities in opposite order i.e. larger element on the left side of the root and smaller element in the right... which I have changed in the code below.
Node Class:
class node:
def __init__(self,data):
self.data = data
self.left = None;
self.right = None;
Tree Class:
class tree:
def __init__(self):
self.start = None;
def make_node(self,Node,data):
if(Node == None):
Node = node(data)
if(self.start == None):
self.start = Node
return Node
if(Node.data>data):
Node.left = self.make_node(Node.left,data)
elif(Node.data<=data):
Node.right = self.make_node(Node.right,data)
return Node
def inorder(self,root):
if(root==None):
return
self.inorder(root.left)
print(root.data)
self.inorder(root.right)
Building a tree and using inorder Function:
BST = tree()
BST.make_node(BST.start,2)
BST.make_node(BST.start,3)
BST.make_node(BST.start,4)
BST.make_node(BST.start,5)
BST.inorder(BST.start)
Upvotes: 1
Reputation: 1
You can check the recursion limit with sys.getrecursionlimit:
import sys print(sys.getrecursionlimit())
then change the limit with sys.getrecursionlimit():
sys.setrecursionlimit(10**6)
Upvotes: 0