Replace recursion by iteration