The following are the steps required to perform a Preorder Traversal DFS:
- Add the root node to a
stack
. For the example tree in this article, the nodeA
will be added to the stack. - Pop the item from the stack and print/process it. The
node A
will be printed. - Add the right child of the node popped in step 2 to the stack and then add the left child to the stack. Because the nodes are traversed from left to right in Preorder Traversal, the node added last in the stack (the left node) will be processed first. In this case, the nodes C and B will be added to the stack, respectively.
- Repeat steps 2 and 3 until the stack is empty.