The main program leads Kara to the tree, calling the method invertLeaf before each step. This method tests whether Kara is on a leaf; if yes, Kara picks it up, if no, Kara puts one down.
def invertLeaf():
if kara.onLeaf():
kara.removeLeaf()
else:
kara.putLeaf()
invertLeaf()
while not kara.treeFront():
kara.move()
invertLeaf()