I am given an array of integers and I would like to convert into a BST;
class BST:
def __init__(self,value):
self.right = None
self.left = None
self.value = value
def insert(self, value):
if value<self.value:
if not self.left:
self.left = BST(value)
else:
self.left.insert(value)
else:
if not self.right:
self.right = BST(value)
else:
self.right.insert(value)
return self
array = [3,10,5,2,7,6,11]
def insertArrayEntryIntoBst(array):
currentNode = BST()
for i in range(len(array)):
currentNode.insert(array[i])
Challenges that I have:
How do I
initialise the BST? - in theinsert() functiondo I need to start with a line that readsif not currentNode: BST(array[0])?After initialising, is my code correct for
insertArrayEntryIntoBst()? The idea is simply to loop through the input array and let theinsert()function do its magic.Do I need a
valueargument in this case? - since the integer value in the array will represent both the node and its value? (which will always be the same thing)
CodePudding user response:
You may construct first node outside loop with the first item of the array.
If you need to access the node. So it can be returned as well.
class BST:
def __init__(self):
self.right = None
self.left = None
self.value = value
def insert(self, value):
if value<self.value:
if not self.left:
self.left = BST(value)
else:
self.left.insert(value)
else:
if not self.right:
self.right = BST(value)
else:
self.right.insert(value)
return self
def insertArrayEntryIntoBst(array):
currentNode = BST(array[0])
for i in range(1,len(array)):
currentNode.insert(array[i])
return(currentNode)
array = [3,10,5,2,7,6,11]
myNode=insertArrayEntryIntoBst(array)
print(myNode.value);
print(myNode.left.value);
print(myNode.right.value);
