Reorganize tree generation code