Skip to content

Instantly share code, notes, and snippets.

@Spockuto
Created October 25, 2016 17:47
Show Gist options
  • Save Spockuto/9f58b62bda706940646539c371f164d4 to your computer and use it in GitHub Desktop.
Save Spockuto/9f58b62bda706940646539c371f164d4 to your computer and use it in GitHub Desktop.
#include<stdio.h>
#include<stdlib.h>
#include<iterator>
using namespace std;
struct node
{
char data;
struct node* left;
struct node* right;
};
int search(char arr[], int strt, int end, char value);
struct node* newNode(char data);
struct node* buildTree(char in[], char pre[], int inStrt, int inEnd)
{
static int preIndex = 0;
if(inStrt > inEnd)
return NULL;
struct node *tNode = newNode(pre[preIndex++]);
if(inStrt == inEnd)
return tNode;
int inIndex = search(in, inStrt, inEnd, tNode->data);
tNode->left = buildTree(in, pre, inStrt, inIndex-1);
tNode->right = buildTree(in, pre, inIndex+1, inEnd);
return tNode;
}
int search(char arr[], int strt, int end, char value)
{
int i;
for(i = strt; i <= end; i++)
{
if(arr[i] == value)
return i;
}
}
struct node* newNode(char data)
{
struct node* node = (struct node*)malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
void printInorder(struct node* node)
{
if (node == NULL)
return;
printInorder(node->left);
printf("%c ", node->data);
printInorder(node->right);
}
bool isIsomorphic(node* n1, node *n2)
{
if (n1 == NULL && n2 == NULL)
return true;
if (n1 == NULL || n2 == NULL)
return false;
if (n1->data != n2->data)
return false;
return
(isIsomorphic(n1->left,n2->left) && isIsomorphic(n1->right,n2->right))||
(isIsomorphic(n1->left,n2->right) && isIsomorphic(n1->right,n2->left));
}
int main()
{
char pre[] = {'1' , '2' , '4' , '5' , '7' , '8' , '3' , '6'};
char in[] = {'4' , '2' ,'7' , '5' , '8' , '1' , '6' , '3'};
int len = sizeof(in)/sizeof(in[0]);
struct node *n1 = buildTree(in, pre, 0, len - 1);
struct node *n2 = buildTree(in, pre, 0, len - 1);
/*Get from file
Store them in pre and in
Construct BuildTree*/
printInorder(n1);
printf("\n");
printInorder(n2);
printf("\n");
if (isIsomorphic(n1, n2) == true)
printf("Yes\n");
else
printf("No\n");
getchar();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment