restructured, working for DFS and BFS