Saturday 28 July 2012

Write a program to construct tree from its pre-order traversal node.





#include<stdio.h>
#include<stdlib.h>


struct node
{
    int data;
    struct node *left;
    struct node *right;
};


struct node *newNode(int data)
{
    struct node *temp= (struct node *)malloc (sizeof(struct node));
    temp->data= data;
    temp->left = NULL;
    temp->right = NULL;
    return temp;
}


struct node *construct_Tree_Util(int pre[],char preLN[],int *index_ptr,int n)
{
    int index = *index_ptr;
    if(index == n)
        return;
    struct node *temp= newNode(pre[index]);
    (*index_ptr)++;


    if(preLN[index]!='L') // L -> leaf node , if leaf node stop constructing tree ther wise construct tree.
    {
    temp->left = construct_Tree_Util(pre,preLN,index_ptr,n);
    temp->right = construct_Tree_Util(pre,preLN,index_ptr,n);
    }
 return temp;
}




struct node *construct_TRee(int pre[],char preLN[],int n)
{
    int index = 0;
    return construct_Tree_Util(pre,preLN,&index,n);
}


printINOrder(struct node *root)
{
    if(root!=NULL)
    {
    printINOrder(root->left);
    printf("%d ",root->data);
    printINOrder(root->right);
    }


}




int main()
{
struct node *root = NULL;
int pre[]={12,14,18,19,16,17,22};
char preLN[]={'N','N','L','L','N','L','L'};
int n= sizeof(pre)/sizeof(int);
root = construct_TRee(pre,preLN,n);
printINOrder(root);
return 0;
}
  


hints:
http://tech-queries.blogspot.in/2011/06/reconstruct-tree-from-pre-order.html

No comments:

Post a Comment