Postorder using 1 stack..


#include <stdlib.h>
#include <iostream>
#include<stack>
using namespace std;

struct node
{
    int data;
    struct node* left;
    struct node* right;
};


struct node* newNode(int data)
{
    struct node* node = (struct node*)malloc(sizeof(struct node));
    node->data = data;
    node->left = NULL;
    node->right = NULL;
    return(node);
}

void PostOrder(node *root) {
    if (!root) return;
    stack<node*> s;
    s.push(root);
    node *prev = NULL;
    while (!s.empty()) {
        node *curr = s.top();
        if (!prev || prev->left == curr || prev->right == curr) {
            if (curr->left)
                s.push(curr->left);
            else if (curr->right)
                s.push(curr->right);
        } else if (curr->left == prev&&curr->right)
            s.push(curr->right);
        else {
            cout << curr->data << " ";
            s.pop();
        }
        prev = curr;
    }
}

int main()
{

    /* Constructed binary tree is
            1
          /   \
        2      3
      /  \
    4     5
  */
    struct node *root = newNode(1);
    root->left        = newNode(2);
    root->right       = newNode(3);
    root->left->left  = newNode(4);
    root->left->right = newNode(5);

    cout<<"\nPreorder traversal of the original tree is \n";
    PostOrder(root);
    return 0;
}

Comments

Popular Posts