Implements treeFold function