change the recursive search into iterative