Refactored recursive solution.