Preorder, Postorder and Inorder Traversal of a Binary Tree using a single Stack

  
#include
using namespace std;
  

struct Node {
    int data;
    struct Node *left, *right;
  
    Node(int data)
    {
        this->data = data;
        left = right = NULL;
    }
};
  

void allTraversal(Node* root)
{
    
    vector pre;
  
    
    vector post;
  
    
    vector in;
  
    
    
    stack s;
  
    
    
    s.push(make_pair(root, 1));
  
    
    
    while (!s.empty()) {
  
        
        
        pair p = s.top();
  
        
        
        if (p.second == 1) {
  
            
            
            s.top().second++;
  
            
            
            pre.push_back(p.first->data);
  
            
            if (p.first->left) {
  
                
                
                s.push(make_pair(
                    p.first->left, 1));
            }
        }
  
        
        
        else if (p.second == 2) {
  
            
            
            s.top().second++;
  
            
            
            in.push_back(p.first->data);
  
            
            if (p.first->right) {
  
                
                
                s.push(make_pair(
                    p.first->right, 1));
            }
        }
  
        
        
        else {
  
            
            
            post.push_back(p.first->data);
  
            
            s.pop();
        }
    }
  
    cout