I have written this code to create a binary tree using given preorder and inorder traversals. According to the dry run I do, there is no problem, and the tree should be created properly. But it is not happening that way. I have printed the inorder of the tree just to check if the tree has been created of the tree. But instead of the inorder, the postorder is being printed. On further investigation I found that the tree itself is not created rightly, that is why the error is coming. There is nothing on the right part of the root which is created. But according to the dry run, there is no problem. Could someone help me find my mistake?
Sample Input: a b d e f c g h j l k d b f e a g c l j h k
Output: dfebgljkhca
#include <stdio.h>
typedef struct Node
{
int data;
struct node *left;
struct node *right;
}node;
typedef node *tree;
tree root=NULL;
char pre[11];
char in[11];
static int i;
void create( tree temp, int start_left, int end_left, int start_right, int end_right )
{
if ( start_left <= end_left )
{
temp->left= (tree) malloc(sizeof( node ));
temp=temp->left;
temp->left=NULL;
temp->right=NULL;
int j;
for ( j=start_left; j<=end_left; j++)
{
if ( pre[i]==in[j] )
{
temp->data=pre[i];
break;
}
}
i++;
create( temp, start_left, j-1, j+1, end_left );
}
if ( start_right <= end_right )
{
temp->right= (tree) malloc(sizeof( node ));
temp=temp->right;
temp->left=NULL;
temp->right=NULL;
int j;
for ( j=start_right; j<=end_right; j++)
{
if ( pre[i]==in [j] )
{
temp->data=pre[i];
break;
}
}
i++;
create( temp, start_right, j-1, j+1, end_right );
}
return ;
}
void inorder_print(tree temp)
{
if ( temp!=NULL )
{
inorder_print(temp->left);
printf("%c",temp->data);
inorder_print(temp->right);
}
}
int main()
{
for( i=0; i<11; i++)
{
scanf("%c", &pre[i]);
fflush(stdin);
}
for( i=0; i<11; i++)
{
scanf("%c", &in[i]);
fflush(stdin);
}
int j;
for( j=0; j<11; j++)
{
if( pre[0]==in[j] )
{
root= (tree) malloc(sizeof( node ));
root->data=pre[0];
root->left=NULL;
root->right=NULL;
break;
}
}
i=1;
create( root, 0, j-1, j+1, 10);
inorder_print(root);
return 0;
}