Welcome back.
Let's now implement the iterative solution for traversing the given binary tree in a post order manner.
And as we have discussed in the previous video, we will be using a stack for this.
And initially we will just fill the root of the given binary tree to the stack.
And we will also be using a visit array to track whether the nodes that have been added to the stack
were added after they were visited, or whether they were added as left and right children.
Okay, and over here we have added the root node.
And in the visit array the first value is going to be false, because at this point the root node has
not been visited.
Okay.
Because if it had been visited, we would have added its left and right children as well to the stack.
Okay.
And we will also need a results array which is initially just empty.
And as we traverse the binary tree we will be adding values to the results array.
And then finally we will be just returning the results array.
Okay.
And as we have discussed in the previous video we are going to have a while loop over here.
And this will keep looping as long as the stack is not empty okay.
And once we are inside the while loop, we are going to pop from the stack and the visit array.
So let me say let car is equal to stack dot pop and let me say let visited is equal to visit dot pop
okay.
And over here we will check whether car is a valid node.
And if that is the case we will check whether visited is true okay.
So if this particular node that we got over here is a node that we did visit, then we would have to
push its value to the results array.
Okay.
But if that is not the case then first we will go ahead and push again this node to the stack.
And at this point in the visit array we will push the value true okay.
Because at this point this node has been added to the stack as a visited node.
Or in other words, we are going to also add its left and right children to the stack over here.
So after this I will say stack, dot, push.
Car dot, right?
Okay.
And in the visit area we will be pushing the value.
False.
Because this node over here has been added to the stack as a right child, not as a root node.
Okay.
Or in other words, the left and right children of this particular node will not be added to the stack
at this point.
Similarly, we will also push the left child to the stack.
So I will say stack dot push car dot left and to the visit array we will push the value false okay.
And that's it.
This should solve the question.
Now let's go ahead and run this code and see if it's passing all the test cases.
And you can see that it's working.
It's passing all the test cases.
So this is how we can implement the postorder traversal of a binary tree in an iterative manner.