Tuesday, 21 October 2014

C++ program to create tree form tree traversals

C++ program to create tree form postorder and inorder tree traversals.


C++ program to create tree from postorder and inorder traversals

#include<iostream>
#include<string.h>
using namespace std;
struct tree_node
{
    char ch;
    tree_node *left,*right;
};
class binary_tree
{
    tree_node *root;
    char post[20],in[20];
public:
    binary_tree()
    {
        root=NULL;
    }
    void get_data();
    tree_node* create(char);
    void cons_tree(tree_node **,int,int,int,int);
    void inorder(tree_node *);
    void postorder(tree_node *);
    void preorder(tree_node *);
    int get_len()
    {
        return strlen(post)-1;
    }
    tree_node** get_root()
    {
        return &root;
    }
};
void binary_tree::get_data()
{
    cout<<"Enter the Postorder Traversal : ";
    cin>>post;
    cout<<"Enter the Inorder Traversal : ";
    cin>>in;
}
tree_node* binary_tree::create(char ch)
{
    tree_node *ne;
    ne=new tree_node;
    ne->ch=ch;
    ne->left=ne->right=NULL;
    return ne;
}
void binary_tree::cons_tree(tree_node **temp,int ps,int pe,int is,int ie)
{
    int j,k,l,pos=-1;
    char next;
    if(post[pe]==0)
        return;
    *temp=create(post[pe]);
    for(l=0;in[l]!=post[pe];l++);
    if((l==0&&in[l+1]==0)||(in[l-1]==0&&in[l+1]==0))
    {
        in[l]=post[pe]=0;
        return;
    }
    in[l]=0;post[pe]=0;
    for(j=is;j<l;j++)
    {
        for(k=ps;;k++)
        {
            if(in[j]==post[k])
                break;
        }
        if(pos<k)
        {
            pos=k;
            next=in[j];
        }
    }
    cons_tree(&((*temp)->left),ps,pos,is,l-1);
    cons_tree(&((*temp)->right),pos+1,pe-1,l+1,ie);
}
void binary_tree::inorder(tree_node *temp)
{
    if(temp==NULL)
        return;
    inorder(temp->left);
    cout<<temp->ch<<" ";
    inorder(temp->right);
}
void binary_tree::postorder(tree_node *temp)
{
    if(temp==NULL)
        return;
    postorder(temp->left);
    postorder(temp->right);
    cout<<temp->ch<<" ";
}
void binary_tree::preorder(tree_node *temp)
{
    if(temp==NULL)
        return;
    cout<<temp->ch<<" ";
    preorder(temp->left);
    preorder(temp->right);
}
int main()
{
    binary_tree tree;
    tree.get_data();
    tree.cons_tree(tree.get_root(),0,tree.get_len(),0,tree.get_len());
    cout<<"Tree successfully created "<<endl;
    cout<<"Inorder traversal   : ";
    tree.inorder(*(tree.get_root()));
    cout<<endl;
    cout<<"Preorder traversal  : ";
    tree.preorder(*(tree.get_root()));
    cout<<endl;
    cout<<"Postorder traversal : ";
    tree.postorder(*(tree.get_root()));
    return 0;
}

No comments:

Post a Comment