c program to find Binary Tree operations

 Program


#include <stdio.h>

#include <stdlib.h>

 struct tnode {

        int data;

        struct tnode *left, *right;

  };

struct tnode *root = NULL;

  struct tnode * createNode(int data) 

{

        struct tnode *newNode;

        newNode  = (struct tnode *) malloc(sizeof(struct tnode));

        newNode->data = data;

        newNode->left = NULL;

        newNode->right = NULL;

        return (newNode);

  }

  void insertion(struct tnode **node, int data) 

{

        if (!*node) 

                *node = createNode(data);

         else if (data < (*node)->data) 

                insertion(&(*node)->left, data);

         else if (data > (*node)->data) 

                insertion(&(*node)->right, data);

        

  }

  void postOrder(struct tnode *node) 

{

        if (node) 

      {

                postOrder(node->left);

                postOrder(node->right);

                printf("%d  ", node->data);

        }

        return;

  }

  void preOrder(struct tnode *node)

 {

        if (node) 

    {

                printf("%d  ", node->data);

                preOrder(node->left);

                preOrder(node->right);

     }

        return;

  }

  void inOrder(struct tnode *node) 

{

        if (node) 

     {

                inOrder(node->left);

                printf("%d  ", node->data);

                inOrder(node->right);

       }

        return;

  }


  int main() 

{

                int data, ch;

                printf("1. Insertion\t2. Pre-order\t3. Post-order\t4. In-order\t5. Exit");

                while (1) {

                printf("\nEnter your choice:");

                scanf("%d", &ch);

                switch (ch) {

                       case 1:

                                printf("Enter your data:");

                                scanf("%d", &data);

                                insertion(&root, data);

                                break;

                        case 2:printf("Pre-order traversal:");

                                preOrder(root);

                                break;

                        case 3:printf("Post-order traversal:");

                                postOrder(root);

                                break;

                        case 4:printf("In-order traversal:");

                                inOrder(root);

                                break;

                        case 5:

                                exit(0);

                        default:

                                printf("Invalid choice\n");

                                break;

                }

        }

        return 0;

  }


 Output



 


 


Comments

Popular posts from this blog

ALGORITHM