2

I am trying to write a function that inserts a node into a binary search tree. I have seen several examples and it seems to me that my algorithm should be working, but it is failing the test for some reason.

def insert(tr, el):
    """ function to insert an element into a binary search tree
    following the rules of binary search trees.
    
    return: an updated tree
    precondition: assumed all elements unique
    """

    if tr == None: 
        return createEyecuBST(el, None)
    elif el < tr.value:
        if tr.left == None:
            tr.left = createEyecuBST(el, tr)
            return tr
        else: return insert(tr.left, el)
    elif el > tr.value:
        if tr.right == None:
            tr.right = createEyecuBST(el, tr)
            return tr
        else: return insert(tr.right, el)
    return None

6
  • Are you intending to have an empty function body, or is this a formatting error? Commented Nov 15, 2014 at 18:12
  • @Tritium21 I'm sorry, I dont understand what you mean. Are you saying you can't see what is inside the insert function? Commented Nov 15, 2014 at 18:15
  • I am saying, the code as posted has nothing in the function body. its not indented. Commented Nov 15, 2014 at 18:16
  • Ah. I see what you mean that's a formatting error. All the code there should be inside the insert function. I' Commented Nov 15, 2014 at 18:17
  • 1
    Some nitpicks. Don't check if a value is None with ==, use the is operator. also, don't end your function with return None, python does that for you :) Commented Nov 15, 2014 at 18:31

1 Answer 1

1

There are two lines which appear problematic in your code:

else: return insert(tr.left, el)

and

else: return insert(tr.right, el)

In those cases your function will return a subtree (either the left or the right one) of tr whereas you want your function to return the updated tr tree. I think you should replace these lines by:

else:
    insert(tr.left, el)
    return tr

And similarly for tr.right.

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.