change recursion in tree search algorithm to looping