I'm sorry. It was my fault I didn't gave details. My code is exactly like the one you gave me.
The thing is that I don't always get an error. When I open a new document or an old one I try to delete all the items in the list. If the last item is selected, the list is cleared and nothing happens. But if any other item but the last one is selected, I get an assertion error. It's very confusing. I thought that it has something to do with the item's handle (HTREEITEM), but I'm not sure.