Fix some memory management bugs with trees