Rewrite tree-pruning algorithm

I was experiencing trouble from collapsing C functions that called
Julia functions. This rewrites the algorithm so it progresses first
to the leaves and then works its way back inwards.