Write a recursive function to traverse a nested data structure, and discuss how you would optimize it to prevent stack overflow.