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 in order tree traversal : For this we will be using stack to keep track of the traversed nodes.

        public void IterativeInorder(TreeNode node)
        {
            Stack<TreeNode> parentStack = new Stack<TreeNode>();

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