implement efficient algorithm for building trees