Sunday 23 December 2018

Tree traversal (preorder,inorder,postorder) using linklist (c++)



#include<iostream>
using namespace std;

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

/**********Element insertion*****************/

node* insert(node *root,int data)
{
    if(root==NULL)
    {
        root=new node();
        root->data=data;
        root->left=root->right=NULL;
    }
    else if(data<=root->data)
    {
        root->left=insert(root->left,data);
    }
    else
    {
        root->right=insert(root->right,data);
    }
    return root;
}

/*************Printing in preorder*************/

void preorder(node *root)
{
    if(root==NULL)
    return;

    cout<<" "<<root->data;
    preorder(root->left);
    preorder(root->right);
}

/**************printing in inorder************/

void inorder(node *root)
{
    if(root==NULL)
    return;

    inorder(root->left);
    cout<<" "<<root->data;
    inorder(root->right);
}

/**********printing in postorder************/

void postorder(node *root)
{
    if(root==NULL)
    return;
    postorder(root->left);
    postorder(root->right);
    cout<<" "<<root->data;

}

/**************Driver Function***********/
int main()
{
    node *root=NULL;

    root=insert(root,10);
    root=insert(root,20);
    root=insert(root,30);
    root=insert(root,15);
    root=insert(root,9);
    root=insert(root,25);


    cout<<"\n preorder"<<endl;
    preorder(root);
    cout<<"\n Inorder"<<endl;
    inorder(root);
    cout<<"\n Postorder"<<endl;
    postorder(root);
    cout<<endl;


    return 0;
}

output:


0 comments:

Post a Comment