Rewrote traverse as a loop to avoid recursion depth error