PreOrder and Inorder traversal of Tree using 2 queues.
#include<stdio.h>
#include<queue>
#include <stdio.h>
#include <stdlib.h>
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);
}
class Stack_As_Queue
{
queue<struct node *> queue1;
queue<struct node *> queue2;
public:
void fix_Queue(queue<struct node *> &to,queue<struct node *> &from)
{
while(!from.empty())
{
to.push(from.front());
from.pop();
}
}
struct node *pop()
{
if(!queue1.empty())
{
struct node *ret = queue1.front();
queue1.pop();
return ret;
}
else if(!queue2.empty())
{
struct node *ret = queue2.front();
queue2.pop();
return ret;
}
return NULL;
}
void push(struct node *num)
{
if(queue1.empty())
{
queue1.push(num);
fix_Queue(queue1,queue2);
}
else if(queue2.empty())
{
queue2.push(num);
fix_Queue(queue2,queue1);
}
}
bool empty()
{
if(!queue1.empty()||!queue2.empty())
return 0;
return 1;
}
void Preorder(struct node *head)
{
while(!empty()||head)
{
while(head)
{
printf("%d ",head->data);
push(head);
head=head->left;
}
if(head=pop())
{
head=head->right;
}
}
}
void Inorder(struct node *head)
{
while(!empty()||head)
{
while(head)
{
push(head);
head=head->left;
}
if(head=pop())
{
printf("%d ",head->data);
head=head->right;
}
}
}
};
int main()
{
/* Constructed binary tree is
1
/ \
2 3
/ \
4 5
*/
Stack_As_Queue q;
struct node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
printf("Preorder traversal of the original tree is \n");
q.Preorder(root);
printf("\nInorder traversal of the original tree is \n");
q.Inorder(root);
return 0;
}
Comments
Post a Comment