Solution Review: Print Depth First Without Using the Recursion

Let’s go through the detailed solution review of the challenge given in the previous lesson.


Typically, the depth-first traversal of a tree is done by using the system stack recursion. However, the same can be implemented by using a stack data structure as well. The following code demonstrates the latter approach. In the beginning, root node reference is added to the stack. The whole tree is traversed until the stack is empty. In each iteration, an element is popped from the stack and its value is printed to the screen. Then the right child and the left child of the node are added to the stack.

Solution code

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.