Implemented recursive algorithm.