Given two n-ary tree's the task is to check if they are mirror of each other or not. - Codeprg

Breaking

programing News Travel Computer Engineering Science Blogging Earning

Saturday, 11 July 2020

Given two n-ary tree's the task is to check if they are mirror of each other or not.

Given two n-ary tree's the task is to check if they are mirror of each other or not.

Given two n-ary tree's the task is to check if they are mirror of each other or not.


Example

     1                    1
   /    \                 /   \
 2      3             3     2

Output: 1

    1                      1
   /  \                    /  \
 2    3                2    3

Output: 0

Note: you may assume that root of both the given tree as 1.

For each test case in a new line print 1 if both the trees are mirrors of each other else print 0.

For Input:
2
3 2
1 2 1 3
1 3 1 2
7 7
1 2 1 3 2 4 2 5 5 6 6 7 6 9
1 3 1 2 2 5 2 4 5 6 6 9 6 7
Your Output is:
1
1

#include<bits/stdc++.h>

using namespace std;

int main() {
    //code
    int t;
    cin >> t;
    while (t--) {
        int n, e, x, y;
        cin >> n >> e;
        stack < int > s[e + 1];
        for (int i = 0; i < e; ++i) {
            cin >> x >> y;
            s[x].push(y);
         //pushing the child correspond to parent.
        }
        int res = 1;
        for (int i = 0; i < e; ++i) {
            cin >> x >> y;
            if (res == 1)
//when top of stack correspond to parent same to y. bcz stack work on LIFO.
// then pop the top element correspond to that parent and res =1;
                if (s[x].top() == y) {
                    s[x].pop();
                    res = 1;
                } else {
// if not equal to y that mean there is no mirror
                    res = 0;
                }
        }

        if (res)
            cout << 1 << endl;
        else
            cout << 0 << endl;


    }
    return 0;
}