top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Print mirror of a binary tree.

0 votes
277 views

consider a tree: enter image description here

Then print it's mirror, in this case it would be: 30 40 20 25 15 45 37

posted Jun 12, 2016 by Shubham Sharma

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote
 
Best answer

I have used Level Order traversal to do so (level order is implemented by queue in function mirrorPrint()), point to be noted here is that my tree will take input as long as input is not 0 which is correct in this case, otherwise you can change the tree according to your need.

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

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

struct node *root=NULL;
int count=1;

struct node *createBtree(struct node *p,int nodeValue){
    if(p==NULL){
        p=(struct node *)malloc(sizeof(struct node));
        p->right=p->left=NULL;
        p->value=nodeValue;
        count++;
    }
    else{
        if(count%2==0)
            p->left=createBtree(p->left,nodeValue);
        else
            p->right=createBtree(p->right,nodeValue);

    }
    return p;
}

void mirrorPrint(struct node *p){
    struct node *tmp;
    if(root==NULL)
        return;
    queue <struct node *> myQueue;
    myQueue.push(root);
    while(!myQueue.empty()){
       tmp=myQueue.front();
       cout << tmp->value << ' ';
       myQueue.pop();
       if(tmp->right!=NULL)
         myQueue.push(tmp->right);
      if(tmp->left!=NULL)
       myQueue.push(tmp->left);
    }
}
int main(){
    int nodeValue;
    cin >> nodeValue;
    while(nodeValue){
        root=createBtree(root,nodeValue);
        cin >> nodeValue;
    }
    mirrorPrint(root);

}
answer Jun 12, 2016 by Shahsikant Dwivedi
...