Binary Search Tree Insert, TreeMax, TreeMin and Search Node in C

Description

This program is used to Insert node and Find Biggest Element, Smallest element and Search from 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;
}
int treeMin(struct node *temp)
{
 if(temp == NULL)
  printf("\nTree is Empty");
 else
 {
  while(temp->left!=NULL)
   temp = temp->left;
 }
 return temp->data;
}
int treeMax(struct node *temp)
{
 if(temp == NULL)
  printf("\nTree is Empty");
 else
 {
  while(temp->right!=NULL)
   temp = temp->right;
 }
 return temp->data;
}
void search(struct node *temp,int d)
{
 if(temp == NULL)
  printf("\nElement not found");
 else if(d==temp->data)
  printf("\nElement %d is found",d);
 else if(d<temp->data)
  search(temp->left,d);
 else
  search(temp->right,d);
}
void main()
{
 int input,ch,data,flag;
 printf("----Binary Search Tree----");
 do
 {
  
  printf("\n\n1.Insert \n2.Tree Minimum\n3.Tree Maximum\n4.Search\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:
    data=treeMin(root);
    printf("\nTree Minimum: %d",data);
    break;
   case 3:
    data=treeMax(root);
    printf("\nTree Maximum: %d",data);
    break;
   case 4:
    printf("\nEnter data to be Searched: ");
    scanf("%d",&data);
    search(root,data);
    break;
   case 5:
    printf("\n----Thank You----\n");break;
   default:
    printf("\nINVALID INPUT !!!\n");
  }
 }while(input!=6);
}

OUTPUT

Binary Search tree Output 1 Binary Search tree Output 2
Binary Search tree Output 3

Labels: