We have already have post on various tree traversal in recursive way. Today we will cover how we can traverse a tree in iterative way.

Iterative Pre order tree traversal : For this we will be using stack to keep track of the traversed nodes

        public void iterativePreorder(TreeNode node)
        {

            bool done = false;
            Stack<TreeNode> parentStack = new Stack<TreeNode>();
            while (!done)
            {
                if (node == null && parentStack.Count() == 0)
                {
                    done = true;
                    return;
                }
                if (node != null)
                {
                    Console.Write(node.Data + " >");
                    parentStack.Push(node.Right);
                    node = node.Left;
                }
                else
                {
                    node = parentStack.Pop();
                }

            }
        }