tree reduce implementation