Welcome back.
Let's now implement the method that you have discussed in the previous video to traverse the given binary
tree in a preorder manner.
And again, as we have discussed, this is going to be the iterative solution.
Okay.
So we are given the root of the binary tree over here.
And first itself we can check if the binary tree which is given to us is empty.
And if that is the case then we will just return an empty array.
Okay.
Now let's proceed.
And in the question notice it's mentioned that as we traverse the given binary tree, we will have to
take the value of the nodes and add it to an array, and then finally return that array.
So for that let's create an array which I'm calling rez.
And as we traverse the binary tree we will be adding values to this array.
And finally we will be returning this array okay.
And as we have discussed in the previous video, we are going to use a stack for this solution.
And initially we are going to fill the root of the tree which is given to us to the stack over here.
Okay.
And then we are going to have a while loop.
And this will keep looping as long as something is there in the stack.
So if there is something in the stack then we are going to pop from the stack.
And when we pop, we are going to get a node.
And let me store that over here.
So let's say let node is equal to stack dot pop okay.
So we're getting a node over here.
And at this point we will push the value of this particular node to the results array.
So I can say rest dot push node dot val okay.
And then as we've discussed in the previous video, first we are going to check whether this particular
node has a right child.
And if it does we'll add that particular node to the stack.
And again remember we are adding the node to the stack, not the value of that particular node to the
stack.
Because at a later point when we pop from the stack and get that node, we would want to check whether
that particular node has a right and left child.
Okay.
So over here let's implement that.
So if this particular node has a right child then we are going to push this particular node to the stack
okay.
And then we're going to check if this node has a left child.
And if it does again we're going to push this particular node to the stack.
And that's it.
So this should help us solve this question okay.
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 preorder traversal for a binary tree in an iterative manner.