recursive solution for encode