Reputation: 21
I need to create a function that creates a BST from an array, in python. The array is already sorted.
The example is:
function array_to_binary_search_tree(array, start, end)
if start > end
Return an empty value
mid := int((start + end) / 2)
tree := BinaryTree()
tree.node := array[mid]
tree.left := array_to_binary_search_tree(array, start, mid - 1)
tree.right := array_to_binary_search_tree(array, mid + 1, end)
Return 'tree'
I have this:
class BST:
def __init__(self,tree,info):
self.right = None
self.left = None
self.info = info
def arrayToBST(seq):
if (seq == []):
return None
mid = ((len(seq)) // 2)
tree = BST(seq[mid])
tree.left = arrayToBST(seq[0:mid])
tree.right = arrayToBST(seq[mid+1:])
return tree
if __name__ == "__main__":
seq = [1,2,3,4,5,6,7,8,9]
arrayToBST(seq)
The result is:
NameError: name 'arrayToBST' is not defined
I don't see the error. Please help, thanks!
Upvotes: 2
Views: 1600
Reputation: 184345
In your recursive call, you are calling the arrayToBST
method of an instance. Therefore, you need to call self.arrayToBST
not just arryToBST
. The entire point of self
is to let you access attributes on your instance.
You should also create an instance and call that instance's arrayToBST
method in your main section.
Upvotes: 1