I made this program but need help in optimizing this algo. It was actually asked in an interview as now I have made it in the best possible way I could I would like to optimize it if there is any chance of doing it.
The input is:
a(b(cd)e(fg))
The output should be:
a
/ \
b e
/ \ / \
c d f g
My current code is:
#include<stdio.h>
#include<malloc.h>
#include<string.h>
struct node
{
char x;
struct node *left;
struct node *right;
}*root;
char a[30];
int i=0,n;
void tre(struct node * p) //function that I am using to convert the string to a tree
{
if(a[i]=='(')
{
i++;
struct node *temp=malloc(sizeof(struct node));
temp->x=a[i];
temp->left=temp->right=NULL;
i++;
if(p->left==NULL)
{
p->left=temp;
tre(p->left);
}
if(a[i]!='('&&a[i]!=')')
{
struct node *tempp=malloc(sizeof(struct node));
tempp->x=a[i];
i++;
p->right=tempp;
tre(p->right);
}
}
else
if(a[i]==')')
{
i++;
}
}
void inorder(struct node *p)//inorder traversal of the tree made
{
if(p!=NULL)
{
inorder(p->left);
printf("%c ",p->x);
inorder(p->right);
}
}
main()
{
printf("Enter the string : ");
scanf("%s",a);
struct node *temp=malloc(sizeof(struct node));
temp->x=a[i];
temp->left=temp->right=NULL;
i++;
root=temp;
tre(root);
inorder(root);
}