recursion replaced with an std::stack