#include <iostream>
using namespace std;
struct NODE
{
NODE *lchild;
int data;
NODE *rchild;
};
class Queue
{
private:
NODE **A;
int size;
int front;
int rear;
public:
Queue(int=0);
bool isEmpty();
void enqueue(NODE*);
NODE *dequeue();
};
Queue::Queue(int size)
{
this->size = size;
*A = new NODE[size];
rear = -1;
front = -1;
}
bool Queue::isEmpty()
{
return (rear==front);
}
void Queue::enqueue(NODE *r)
{
if(rear == size)
cout<<"Queue is full!";
else
{
A[++rear]=r;
cout<<"enqueue successful: "<<r->data<<endl;
}
}
NODE* Queue::dequeue()
{
NODE *r=nullptr;
if(isEmpty())
cout<<"Queue is Empty";
else
{
r=A[++front];
cout<<"dequeue successful "<<r->data<<endl;
}
return r;
}
class Tree
{
private:
NODE *root;
public:
void createTree();
};
void Tree::createTree()
{
NODE *p, *t;
int x;
Queue q(1000);
cout<<"Enter data:";
cin>>x;
root = new NODE;
root->data = x;
root->lchild=nullptr;
root->rchild=nullptr;
q.enqueue(root);
while(!q.isEmpty())
{
p = q.dequeue();
cout<<"Enter left child of "<<p->data<<", insert -1 for no child: ";
cin>>x;
if(!(x==-1))
{
t = new NODE;
t->data = x;
t->lchild=nullptr;
t->rchild=nullptr;
p->lchild = t;
q.enqueue(t);
}
cout<<"Enter right child of "<<p->data<<", insert -1 for no child: ";
cin>>x;
if(!(x==-1))
{
t = new NODE;
t->data = x;
t->lchild=nullptr;
t->rchild=nullptr;
p->rchild = t;
q.enqueue(t);
}
}
}
int main()
{
Tree t;
t.createTree();
return 0;
}
Input:
5 8 6 -1 9 3 -1 4 2
Problem is: Program terminates abruptly after taking 2 as right child of 9 while it should ask for child of 3 4 2