Code for traverse and topological sort of DAG