how to define the algorithm using trees?