Postorder using two stacks..


#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;
  stack<node*> output;
  s.push(root);
  while (!s.empty()) {
    node *curr = s.top();
    output.push(curr);
    s.pop();
    if (curr->left)
      s.push(curr->left);
    if (curr->right)
      s.push(curr->right);
  }
  while (!output.empty()) {
    cout << output.top()->data << " ";
    output.pop();
  }
}
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