Move tree building to its own function. Both parts can use the same tree. This also decreaseas memory usage by one element by row :D