educative.io

Educative

How is this solution depth-first?

In reviewing the solution using stack, this does not seem like DFS. We are adding adjacent nodes at each level to the stack and iterating over it - just like BFS. I understand that we used Queue in the BFS solution, but the fact remains that we are still adding nodes at each level first.
Also, how one would account for in-order, pre-order, or post-order traversal with this implementation? Maybe I am missing something here.

Thank you for taking the time to answer my question!


Type your question above this line.

Course: https://www.educative.io/collection/10370001/5347133077061632
Lesson: https://www.educative.io/collection/page/10370001/5347133077061632/6602786110177280

Hi @Khurram_Haroon.
When running DFS using stack, you are correct to say that we are adding adjacent nodes of the current level into the stack like BFS implementation with the queue. But we are also popping one element right afterward and then adding its adjacent nodes in the stack. This results the DFS effect we desire.
firefly