There are 2 ways of doing that
- DFS
- BFS
For the DFS way start with node n, if it is not visited, mark it visited, and then see what all node it points to, go over each of them. Once you are done with a node completely, then add this node to the ans.
For the BFS way, use a queue and find the indegree of each of the nodes, at each iteration loop over all the nodes with indegree == 0, then go over each of the node that it points to, for each of those pointed nodes reduce the indegree of those nodes by 1. Once we explored the node with indegree == 0 add it to the ans list.