Solved programming problem

Check two tree is mirror to each other or not in C++.

Source code

#include <iostream>

using namespace std;

struct tree

{

    char data;

    struct tree *right,*left;

};

int a[100],b[100];

typedef struct tree node;

node *root=NULL;

node *root1=NULL;

int i=0,j=0;

void preorderprint(node *root)

{

    cout<<root->data<<" ";

    a[i]=root->data; ///save the 1st tree data to a array

    i++;

    if(root->left!= NULL)

    {

        preorderprint(root->left);

    }

    if(root->right!= NULL)

    {

        preorderprint(root->right);

    }

}

void postorderprint(node *root1)

{

    if(root1->left!= NULL)

    {

        postorderprint(root1->left);

    }

    if(root1->right!= NULL)

    {

        postorderprint(root1->right);

    }

    b[j]=root1->data;///save the 2nd tree data to b array

    j++;

    cout<<root1->data<<" ";

}

void createtree(node *root)

{

    int ans;

    cout<<root->data<<" Has Any Left Child?";

    cin>>ans;

    if(ans==1)

    {

        root->left = new node();

        cin>>root->left->data;

        createtree(root->left);

    }

    else

    {

        root->left = NULL;

    }

    cout<<root->data<<" Has Any Right Child?";

    cin>>ans;

    if(ans==1)

    {

        root->right = new node();

        cin>>root->right->data;

        createtree(root->right);

    }

    else

    {

        root->right = NULL;

    }

}

void mir()

{

    i=0;

    j--;

    int f=0;

    while(j>=0)

    {

        if(a[i]==b[j])

        {

            i++;

            j--;

        }

        if(a[i]!=b[j])

        {

            f=1;

            cout<<"
False"<<endl;

            return;

        }

    }

    if(f==0)

    {

        cout<<"
True"<<endl;

    }

}

int main()

{

    root = new node();

    cout<<"Root :"<<endl;

    cin>>root->data;

    createtree(root);

    preorderprint(root);

    root1 = new node();

    cout<<"
Root :"<<endl;

    cin>>root1->data;

    createtree(root1);

    postorderprint(root1);

    mir();

    return 0;

}

Output

Root :
1
1 Has Any Left Child?1
2
2 Has Any Left Child?0
2 Has Any Right Child?0
1 Has Any Right Child?1
3
3 Has Any Left Child?0
3 Has Any Right Child?0
1 2 3
Root :
1
1 Has Any Left Child?1
3
3 Has Any Left Child?0
3 Has Any Right Child?0
1 Has Any Right Child?1
2
2 Has Any Left Child?0
2 Has Any Right Child?0
3 2 1
True

Join the discussion

Add your comment