It does not actually solve the problem, but after some more careful googling I discovered that this is due to incompatibility between jQuery and Treeview versions. (I am using the latest of both). Anyway, the workaround to this is to use animated property. This is what I noticed also in this example, which it worked unlike my code. The only difference was the use of the animated property, but I didn't believe it only to come across this page, thankfully only a few minutes later.
As I said it doesn't solve the problem, not only because it is a workaround, but because it breaks again after some collapses, expansions and toggling. However, it is not that obvious now (previously it only took one collapse to break), it won't show to someone using the tree 'sensibly' and after all, at least in my case, it doesn't really affect the functionality. It works for me now.