# Hierarchical Datastructure – Iterative Tree Traversals

This is the second article in the Tree Traversals - Online Classes. This is the sixth article in the series of non-linear data structures, to read more about the previous article, please check the topic Hierarchical Datastructure – Tree Traversals. To get updates on the coming articles in the series, please use the Subscribe feature on the right panel.

## Purpose of article

We are already done with the constructing a binary tree and doing basic operations like creating a tree, adding a node, removing a node and all the traversals. There are situations when we get little confused using the recursive approaches of traversals. To make it more simple, I will try to demonstrate with the help of Iterative Tree Traversals

## Iterative approach for Preorder Traversal

As we already know the definition of preorder traversal, we will directly jump into the algorithm, its explanation and implementation. To traverse a tree in preorder fashion we will employ a stack and we pass the root node of the tree into the preOrder routine/method. The very first thing is to check if the node i.e. root is not null. If it is null then return from the method, because there is nothing to traverse. We will consider the below tree for traversal and below is the pseudo code for the same:

### Pseudo Code

So let us start with an empty stack S and push the ROOT in there, the stack looks like the image below: Now we run an iteration till our stack S is not empty, in each iteration of the loop we pop a node from the stack and visit it(print it). Then we check if the node has a left right child we push the right child on the stack and then if the node has a left child, we put the left child on the stack. We keep executing this set of statements till the stack contains at least one element.