FINDING MIN AND MAX IN BINARY SEARCH TREE

#include<stdio.h>
#include<stdlib.h>

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

struct node* newnode(int data)
{
struct node* newnode = (struct node*)malloc(sizeof(struct node));
newnode->data = data;
newnode->left = NULL;
newnode->right = NULL;
return newnode;
}

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

int search(struct node* root , int data)
{
if(root == NULL) return 0;
else if(root->data == data) return 1;
else if(data <= root->data) return search(root->left,data);
else if(data > root->data) return search(root->right,data);
}

int min(struct node* root)
{
if(root == NULL)
{
return 0;
}
else
{
struct node* current = root;
while(current->left !=NULL)
{
current = current->left;
}
return current->data;
}
}

int max(struct node* root)
{
if(root == NULL)
{
return 0;
}
else
{
struct node* current = root;
while(current->right !=NULL)
{
current = current->right;
}
return current->data;
}
}

int main()
{
int n;
struct node* root = NULL;
struct node* main_root;
root = insert(root,20);
main_root = root;
root = insert(root,15);
root = insert(root,25);
scanf("%d",&n);
if(search(root,n)==1)printf("found\n");
else printf("not found\n");
printf("min is %d\n",min(main_root));
printf("max is %d\n",max(main_root));
return 0;
}

Comments