Traversal Using Stacks
Traversal Using Stacks
1) Let's say we go with the stack approach. The first node we add will always be
the root, in this case 1.
2) When we pop 1 from the stack, we have the option to add node 2 first or
node 3 first. Which node should we push onto the stack first?
(2)
(3)
3) Now that our stack is not empty, we can pop from it again. We pop2 from it,
and again we have to decide whether to push node 4 first or node 5 first.
Again, if we look at our desired traversal outcome from our recursive
approach, we see that 4 should be printed before 5. Following step 2a, it
looks like we should push 5 onto the stack first, followed by 4.
Now we've printed 1 2 and our stack looks like
(4) (5) (3)
4) Again, we pop from our stack. This time we 4 is popped and printed, and
since 4 has no children, we don't add anything, and just keep popping.
After 4 has been popped, we will have printed 1 2 4 and our stack would
then contain:
(5) (3)
Looking at what we've been doing, it looks like a pattern has emerged.
7. Current node is NULL. Pop 5 from stack. Right child of 5 doesn't exist.
Print 5. Set current node to NULL.
Stack: 3, 1, 2
Pseudo Code:
1. Create a Stack.
2. Push the root into the stack and set the root = root.left continue till it hits
the NULL.
3. If root is null and Stack is empty Then
1. return, we are done.
4. Else
1. Pop the top Node from the Stack and set it as, root = popped_Node.
2. print the root and go right, root = root.right.
3. Go to step 2.
5. End If