Added tree building function