Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- using namespace std;
- struct bnode{
- int data;
- struct bnode *l,*r;
- bnode(int data){
- this->data=data;
- l=NULL;
- r=NULL;
- };
- };
- struct queue{
- int size;
- int front;
- int rear;
- struct bnode *elements[50];
- };
- void enqueue(struct queue *Q,struct bnode *T){
- if((Q->rear+1)%Q->size==Q->front) cout<<"queue is full ";
- else{
- if(Q->rear==-1){
- Q->rear=0;Q->front=0;
- }
- else Q->rear=(Q->rear+1)%Q->size;
- Q->elements[Q->rear]=T;
- }
- }
- struct bnode *dequeue(struct queue *Q){
- if(Q->front==-1) cout<<"queue is empty ";
- else{
- struct bnode *t=Q->elements[Q->front];
- if(Q->front==Q->rear){
- Q->front=-1;Q->rear=-1;
- }
- else Q->front++;
- return t;
- }
- }
- void getSibling(struct bnode *T,int x){
- struct queue *Q=new queue();
- Q->front=-1;
- Q->rear=-1;
- Q->size=10;
- enqueue(Q,T);
- struct bnode *e=new bnode(-1);
- enqueue(Q,e);
- struct queue *ans=new queue();
- ans->front=-1;
- ans->rear=-1;
- ans->size=10;
- while(Q->rear!=-1){
- struct bnode *p=dequeue(Q);
- enqueue(ans,p);
- if(p->data==-1){
- if(Q->rear==-1) return ;
- p=dequeue(Q);
- enqueue(Q,e);
- int tag=0;
- while(ans->rear!=-1){
- struct bnode *c=dequeue(ans);
- if(c->data==-1){
- enqueue(ans,c);
- break;
- }
- if(c->data==x){
- tag=1;
- }
- enqueue(ans,c);
- }
- if(tag==1){
- int flag=0;
- while(ans->rear!=-1){
- struct bnode *c=dequeue(ans);
- if(c->data==-1){
- if(flag==0) cout<<-1<<endl;
- return ;
- }
- if(c->data!=x){
- flag=1;
- cout<<c->data<<" ";
- }
- }
- }
- if(tag==0){
- while(ans->rear!=-1){
- dequeue(ans);
- }
- }
- enqueue(ans,p);
- }
- if(p->l!=NULL) enqueue(Q,p->l);
- if(p->r!=NULL) enqueue(Q,p->r);
- }
- }
- void getparent(struct bnode *T,int x,int &p){
- if(T==NULL) return;
- if(T->l!=NULL and T->l->data==x){
- p=T->data;
- return ;
- }
- if(T->r!=NULL and T->r->data==x){
- p=T->data;
- return ;
- }
- getparent(T->l,x,p);
- getparent(T->r,x,p);
- }
- int main(){
- // creating given binary tree
- struct bnode *T=new bnode(4);
- T->l=new bnode(3);
- T->r=new bnode(9);
- T->l->l=new bnode(5);
- T->l->r=new bnode(6);
- T->r->l=new bnode(1);
- T->r->r=new bnode(8);
- // tree created
- int x;
- cout<<"enter node value : "<<endl;
- cin>>x;
- int p=-1;
- getparent(T,x,p);
- if(p!=-1){
- cout<<"parent is "<<p<<endl;
- cout<<"uncle of "<<x<<" is : ";
- getSibling(T,p);
- }
- else{
- cout<<-1<<endl;
- cout<<"no parent therefore no uncle"<<endl;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment