2

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!

3
  • arrayToBST is a member of a class. You need to call it from one instance of this class Commented Jun 22, 2014 at 17:53
  • where is your object of the Class BST? Commented Jun 22, 2014 at 17:55
  • try using: BST().arrayToBST(seq) Commented Jun 22, 2014 at 18:02

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.