while learning about BSTs in hackerrank, I came across the following issue.
My classes for the Node and for the Binary Search Tree is defined as follows:
class Node:
def __init__(self,info):
self.info = info
self.left = None
self.right = None
class BinarySearchTree:
def __init__(self):
self.root = None
def insert(self,val):
currentNode = self.root
if currentNode is None:
self.root = Node(val)
elif currentNode.info > val:
currentNode.left = insert(currentNode.left,val)
elif currentNode.info < val:
currentNode.right = insert(currentNode.right,val)
return currentNode
However, performing a traversal on tree = BinarySearchTree()
after using tree.insert(arr[i]
over a for loop for some array of integers arr
returns no output. The logic seems correct to me, and I suspect that this is due to a difference in type between Node and BST, but I am unsure of how to resolve this.
Edit: below is the full code from hackerrank. The only bit I was able to edit is the insert function.
class Node:
def __init__(self, info):
self.info = info
self.left = None
self.right = None
self.level = None
def __str__(self):
return str(self.info)
def preOrder(root):
if root == None:
return
print (root.info, end=" ")
preOrder(root.left)
preOrder(root.right)
class BinarySearchTree:
def __init__(self):
self.root = None
def insert(self,val):
currentNode = self.root
if currentNode is None:
self.root = Node(val)
elif currentNode.info > val:
currentNode.left = insert(currentNode.left,val)
elif currentNode.info < val:
currentNode.right = insert(currentNode.right,val)
return currentNode
tree = BinarySearchTree()
t = int(input())
arr = list(map(int, input().split()))
for i in range(t):
tree.insert(arr[i])
preOrder(tree.root)
The given test case was
6
4 2 3 1 7 6
and was supposed to return 4 2 3 1 7 6
, but no output was returned.
Edit: made the changes according to the first answer! Now, I have the following week error:
Traceback (most recent call last):
File “solution.py”, line 40, in <module>
tree.insert(arr[i])
File “solution.py”, line 30, in insert
currentNode.left = insert(currentNode.left,val)
NameError: name ‘insert’ is not defined