Skip to content

Instantly share code, notes, and snippets.

@rohit-nsit08
Created August 30, 2011 12:45
Show Gist options
  • Select an option

  • Save rohit-nsit08/1180808 to your computer and use it in GitHub Desktop.

Select an option

Save rohit-nsit08/1180808 to your computer and use it in GitHub Desktop.
tree from inorder and preorder traversal
#include<stdio.h>
#include<stdlib.h>
char in[]= {'d','b','e','a','f','c','g'};
char pre[]={'a','b','d','e','c','f','g'};
int size = sizeof(in);
int pos = 0;
typedef struct node{
char value;
struct node*left;
struct node*right;
}treenode;
treenode* get_tree(int l,int r);
void print(treenode*root);
int search(char val);
void print(treenode*root)
{
if(root==NULL)
return;
print(root->left);
printf("%c",root->value);
print(root->right);
}
int search(char val)
{
int i;
for(i=0;i<size;i++)
{
if(in[i]==val)
return i;
}
return -1;
}
treenode* get_tree(int l, int r)
{
int inpos = search(pre[pos]);
if(l>=r)return NULL;
pos++;
treenode* temp = (treenode*)malloc(sizeof(struct node));
temp->value = in[inpos];
temp->left = get_tree(l,inpos);
temp->right = get_tree(inpos+1,r);
return temp;
}
int main()
{
treenode*root = NULL;
int l = 0;
root = get_tree(l,size);
print(root);
printf("\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment