Changed recursion to iterative