C++ Program for Inorder Tree Traversal without Recursion

If a binary tree is traversed in-order, the left subtree is visited first, then the root and later the right sub-tree. The output the key in ascending order in in_order traversal. This is a C++ Program for Inorder Tree Traversal without Recursion.


   Function inOrder():
      Declare a stack s.
      Declare the current node as root.
      While current node is not null and stack is not empty do
         While current node is not null do
            Push the current node on the top of the stack
            Make the left child node as current node
         Point the current node at the top of the stack.
         Pop the top most node from the stack
         Print the current node.
         Make the right node as current node.  
      Insert some elements at root, left node and right node in stack.
      Call the inOrder() function to traverse the tree. 

Example Code

 Live Demo

using namespace std;

struct n {
   int d;
   struct n* l;
   struct n* r;
   n (int d) {
      this->d = d;
      l = r = NULL;

void inOrder(struct n *root) {
   stack<n *> s;
   n *current = root;

   while (current != NULL || s.empty() == false) {
      while (current != NULL) {
         current = current->l;

      current = s.top();

      cout << current->d << " ";
      current = current->r;

int main() {
   struct n *root = new n(7);

   root->l = new n(6);
   root->r = new n(2);
   root->l->l = new n(1);
   root->l->r = new n(9);

   return 0;


1 6 9 7 2

Updated on: 30-Jul-2019


Kickstart Your Career

Get certified by completing the course

Get Started