Binary Tree Traversal

#include <stdio.h>
#include<malloc.h>

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

node* create()
{
    int x;
    node *T;
    T=(node*)malloc(sizeof(node));
    T->left=NULL;
    T->right=NULL;
    printf("\nEnter data [-1 to end] ");
    scanf("%d",&x);
    if(x==-1)
    {
        T->data=x;
        return T;
    }
    else
    {
        T->data=x;
        printf("Enter left child of %d",x);
        T->left=create();
        printf("Enter right child of %d",x);
        T->right=create();
    }
    return T;
}

void preorder(node *T)
{
    if(T->data!=-1)
    {
        printf("%d ",T->data);
        preorder(T->left);
        preorder(T->right);
    }
}

void inorder(node *T)
{
    if(T->data!=-1)
    {
        inorder(T->left);
        printf("%d ",T->data);
        inorder(T->right);
    }
}

void postorder(node *T)
{
    if(T->data!=-1)
    {
        postorder(T->left);
        postorder(T->right);
        printf("%d ",T->data);
    }
}

int main()
{
    node *root;
    int x;
    printf("Creating a tree\n");
    root=create();
    do
    {
        printf("\n\nEnter\n1.Preorder\n2.Inorder\n3.Postorder\n4.Exit\n");
        scanf("%d",&x);
        switch(x)
        {
            case 1: preorder(root);  break;
            case 2: inorder(root);   break;
            case 3: postorder(root); break;
        }
    }while(x!=4);
    return 0;
}

/*Output
Creating a tree

Enter data [-1 to end] 5
Enter left child of 5
Enter data [-1 to end] 1
Enter left child of 1
Enter data [-1 to end] -1
Enter right child of 1
Enter data [-1 to end] -1
Enter right child of 5
Enter data [-1 to end] 2
Enter left child of 2
Enter data [-1 to end] -1
Enter right child of 2
Enter data [-1 to end] -1

Enter
1.Preorder
2.Inorder
3.Postorder
4.Exit
1
5 1 2

Enter
1.Preorder
2.Inorder
3.Postorder
4.Exit
2
1 5 2

Enter
1.Preorder
2.Inorder
3.Postorder
4.Exit
3
1 2 5

Enter
1.Preorder
2.Inorder
3.Postorder
4.Exit
4
*/

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s