refactored traverse() and added support for printing stdout statements