I'm pretty sure the issue you're encountering is simply that you're not getting the return value you expect from mapInsert
. The current code always returns the node that the provided value was inserted in, even if that is a leaf node somewhere deep in your tree. (And actually, not that I look closely at it there are some additional bugs with what you're recursing on and returning.)
I think you should change your return
statements in the else
block of mapInsert
to return mp
, rather than the result of the recursive call. The result of the call should be assigned to mp.left
or mp.right
, depending on which side we recursed on.
def mapInsert(key, value, mp):
if isinstance(mp, EmptyMap):
return mkNonEmptyMap(mkEmptyMap(), key, value, mkEmptyMap())
else:
if key == mp.key:
mp.value = value
elif mp.key < key:
mp.left = mapInsert(key, value, mp.left) # don't return recursive result
else:
mp.right = mapInsert(key, value, mp.right) # pass the right child here!
return mp # always return mp from this branch
Note that a more "Pythonic" design would probably use methods in a class, rather than a separate function to handle this kind of thing. This would require somewhat different handling of empty trees though.