Move tree code to separate method