Iterative DFS vs Recursive DFS and different elements order

后端 未结 4 1647
时光说笑
时光说笑 2020-11-28 02:38

I have written a recursive DFS algorithm to traverse a graph:

void Graph::DFS(Node n)
{
    std::cout << ReadNode(n) << \" \";

    M         


        
4条回答
  •  没有蜡笔的小新
    2020-11-28 03:13

    The most obvious diff is the order you utilize the children.

    In the Recursive method: You take the first child and run with it as soon as it comes

    while in iterative approach: You push all the children in the stack and then take the top of the stack i.e the last child

    To produce the same result just do the insertion of children in reverse order.

    The other diff would be memory usage as one would use call stack while the other would use a stack that you make or one the STL elements:

    You can read about this here: https://codeforces.com/blog/entry/17307

提交回复
热议问题