Binary Search Tree Insert, InOrder, PreOrder, PostOrder

Description

This program is used to Insert node and InOrder, PreOrder, PostOrder Traversal of Binary Search Tree (BST) in C

#include<stdio.h>
#include<stdlib.h>
struct node
{
 struct node *left;
 int data;
 struct node *right;
};
struct node *root = NULL;

struct node* getNode()
{
 return ((struct node *)malloc(sizeof(struct node)));
}
struct node* insertNode(struct node *root,int x)
{
 struct node *newNode;
 newNode = getNode();
 newNode->data = x;
 newNode->left = NULL;
 newNode->right = NULL;
 if(root == NULL)
 {
  root = newNode;
  return root;
 }
 else if(newNode->data < root->data)
 {
  root->left = insertNode(root->left,x);
 }
 else
  root->right = insertNode(root->right,x);
 return root;
}
void inorder(struct node *root)
{
 if(root)
 {
  inorder(root->left);
  printf("%d\t",root->data);
  inorder(root->right);
 }
}
void preorder(struct node *root)
{
 if(root)
 {
  printf("%d\t",root->data);
  preorder(root->left);
  preorder(root->right);
 }
}
void postorder(struct node *root)
{
 if(root)
 {
  postorder(root->left);
  postorder(root->right);
  printf("%d\t",root->data);
 }
}

void main()
{
 int input,ch,data,flag;
 printf("---------------Binary Search Tree-------------\n");
 do
 {
  printf("\n1.Insert\n2.Inorder\n3.Preorder\n4.Postorder\n5.Exit\n");
  
  printf("\nEnter your choice: ");
  scanf("%d",&input);
  switch(input)
  {
   case 1:
    printf("\nEnter data to be inserted: ");
    scanf("%d",&data);
    root = insertNode(root,data);
    break;
   case 2:
    inorder(root);
    break;
   case 3:
    preorder(root);
    break;
   case 4:
    postorder(root);
    break;
   case 5:
    printf("\n----Thank You----\n");break;
   default:
    printf("\nINVALID INPUT !!!\n");
  }
 }while(input!=5);
}

OUTPUT

Binary Search Tree Output 1 Binary Search Tree Output 2

Labels: