Sorting for trees