Separated the tree building function from main