Iterative way of doing Post-Order Traversal using STACK

Rachitjain
3 min readApr 10, 2022

Let’s get right to the point: you’ve come to learn about the iterative process. Let’s talk about it.
Let’s have a look at what we require :

1. Binary Tree

2. Stack

So let’s quickly understand the given picture and get a straightforward view of post-order traversal:

To reserve the pair of Node and its Count we will require a Stack.

Now we will preform some operations in the declared stack till it gets empty, but before that, we are going to push the root element and its count

Good, now we have one element in the stack. Now we’ll begin our loop condition, which will continue until the stack is empty.

Fair!!,

Now 0,1,2 are the three viable values of the count;
0 → Node is not yet visited.

1 → the value of that node will be printed. Furthermore, in this situation, we are expected to promote its children.

2 → The pair from the stack will pop.

As a result, when we choose the top element of the stack, we have a pair from which we may extract the node and its count.

Now the current state is (node,count) →(1,1). Now that the count is 1 we will print and push its children

Now, when you choose the top element, you’ll notice that it’s the root node’s left child, correct? We are going to print it and push its child since it is (2,0) and as we raise its count it becomes (2,1). The same thing happens again.

When the node has no children, you won’t push anything. Instead, you’ll return to the same element and increase the count until it reaches 2, at which point you’ll pop it.

That’s everything!! This is how you’ll print the binary tree Post-Order.

--

--