refactored code for trees