Add defensive checks to TSTree_ functions