Welcome back.
Let's now implement the iterative solution for inorder traversal of the given binary tree okay.
And again as mentioned in the question, as we traverse the binary tree, we will be adding the values
of the nodes to an array.
And then we'll have to finally return it.
So that's given in the question right.
So let's just call this array rest.
And initially this is going to be an empty array.
And finally we will be just returning rest okay.
Now we will also be using a stack as we have discussed in the previous video.
And this is just going to be an empty array initially.
And we will also need a variable, let's call it cur to store the node where we are currently at.
And initially Cur will just be equal to root.
Okay, now we are going to have a while loop, and inside the while loop we will have two conditions.
Either cur should be pointing to a node or the stack should not be empty.
If either of these conditions is true, we will keep looping.
Okay, now inside the while loop.
Will check whether Kerr is pointing to a node.
Because for the inorder traversal, we have to go as much left as possible.
So if Cur is pointing to a valid node, we will just push it to the stack.
So I can say stack dot, push cur.
Okay.
And then I'll just move more to the left.
So I'll say cur is equal to cur dot left.
Okay.
And once we are out of this while loop over here, cur would be not pointing to a node, it would be
null.
And at that point we will say cur is equal to stack dot pop, or we are just popping from the stack
and we are making that cur.
Okay.
And to the results array we will have to at this point push the value of cur.
So rest dot push car dot val.
And then we have to move to the right.
So curve would be equal to curve dot right.
Okay.
And again this is important.
Notice over here we have gone as much left as possible.
And over here we have explored the root node.
And then we have to explore the right node.
So that's the inorder traversal order right.
So that's it.
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 you can implement the inorder traversal of a given binary tree in an iterative manner.