Check Mirror Tree [ MakeMyTrip, Amazon ]

Problem: Check if two n-ary tree are mirror to each other.

Two trees are mirror if :

  • the key/data value of the root are same of the two trees
  • left sub tree is same as right sub tree of another tree
  • right sub tree is same as left sub tree of another tree

The problem appeared as interview question in Amazon & MakeMyTrip [Courtesy: geeksforgeeks]

#include <stdio.h>
#include <vector>
#include <iostream>

using namespace std;

vector<int> vec[16];
vector<int> vec2[16];

bool checkMirror(int root,int root2)
{
    bool res;
    int i;
    if(root!=root2)
    return false;
    else
    {
        if(vec[root].size()==0 && vec2[root2].size()==0)
        return true;
        if(vec[root].size()!=vec2[root2].size())
        return false;
        for(i=0;i<vec[root].size();i++)
        {
            //cout<<vec[root][i]<<" "<<vec2[root2][vec2[root2].size()-1-i]<<endl;
            res=checkMirror(vec[root][i],vec2[root2][vec2[root2].size()-1-i]);
            if(res==false)
            return false;
        }
        return true;
    }
    return false;
}

int main() {
	//code
	int t,n,i,a,b,e;
	int src,src2;
	scanf("%d",&t);
	while(t--)
	{
	    scanf("%d%d",&n,&e);
	    for(i=0;i<16;i++)
	    {
	        vec[i].clear();
	        vec2[i].clear();
	    }
	    for(i=0;i<e;i++)
	    {
	        scanf("%d%d",&a,&b);
	        if(i==0)
	        src=a;
	        vec[a].push_back(b);
	    }
	    for(i=0;i<e;i++)
	    {
	        scanf("%d%d",&a,&b);
	        if(i==0)
	        src2=a;
	        vec2[a].push_back(b);
	    }
	    
	    bool res = checkMirror(src,src2);
	    if(res)
	    printf("1\n");
	    else
	    printf("0\n");
	}
	return 0;
}

 

Comments are closed.