Objective: Given a binary tree, write a non recursive or iterative algorithm for preorder traversal.
Earlier we have seen “What is preorder traversal and recursive algorithm for it“, In this article we will solve it with iterative/Non Recursive manner.
Since we are not using recursion, we will use the Stack to store the traversal, we need to remember that preorder traversal is, first traverse the root node then left node followed by the right node.
- Create a Stack.
- Print the root and push it to Stack and go left i.e root=root.left and till it hits the NULL.
- If root is null and Stack is empty Then
- return, we are done.
- Pop the top Node from the Stack and set it as, root = popped_Node.
- Go right, root = root.right.
- Go to step 2.
- End If
See the animated image below and code for more understanding.
1 2 4 5 3 6 7 1 2 4 5 3 6 7