Created
September 22, 2014 00:29
-
-
Save rajeshsubhankar/05f082fda92da522236e to your computer and use it in GitHub Desktop.
Check whether 2 binary trees are Isomorphic to each other or not.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<bits/stdc++.h> | |
using namespace std; | |
struct node | |
{ | |
int val; | |
node* left; | |
node* right; | |
}; | |
node* newNode(int val) | |
{ | |
node* temp=(node*)malloc(sizeof(node)); | |
temp->val=val; | |
temp->left=temp->right=NULL; | |
return temp; | |
} | |
bool check(node* l, node* r) | |
{ | |
if(!l || !r) return (!l && !r); | |
return ( (l->val==r->val) && ( (check(l->left,r->left) && check(l->right,r->right)) || (check(l->left,r->right) && check(l->right,r->left)) )); | |
} | |
int main() | |
{ | |
node* root1=newNode(4); root1->left=newNode(2); root1->right=newNode(6); | |
root1->left->left=newNode(1); root1->left->right=newNode(3); | |
root1->right->left=newNode(5); root1->right->right=newNode(7); | |
node* root2=newNode(4); root2->left=newNode(6); root2->right=newNode(2); | |
root2->left->left=newNode(7); root2->left->right=newNode(5); | |
root2->right->left=newNode(3); root2->right->right=newNode(1); | |
//if(root1->val!=root2->val){cout<<"NOT ISOMORPHIC"<<endl; return0;} | |
if(check(root1,root2)) cout<<"ISOMORPHIC"<<endl; | |
else cout<<"NOT ISOMORPHIC"<<endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment