Skip to content

Instantly share code, notes, and snippets.

@shubham100795
Created March 5, 2017 18:47
Show Gist options
  • Save shubham100795/7ece73e43196f7a4253a0f40b78c0cd7 to your computer and use it in GitHub Desktop.
Save shubham100795/7ece73e43196f7a4253a0f40b78c0cd7 to your computer and use it in GitHub Desktop.
Maximum element between two nodes of a BST
#include<stdio.h>
#include<stdlib.h>
#include<limits.h>
struct node{
int data;
struct node *left;
struct node *right;
};
struct node *newnode(int x)
{
struct node* ptr=(struct node*)malloc(sizeof(struct node));
ptr->data=x;
ptr->left=NULL;
ptr->right=NULL;
return ptr;
}
struct node* insert(struct node *root,int x)
{
struct node* par;
if(root==NULL)
{
root=newnode(x);
return root;
}
else
{
struct node *proot=root;
while(proot!=NULL)
{
if(x<proot->data)
{
par=proot;
proot=proot->left;
}
else
{
par=proot;
proot=proot->right;
}
}
if(x<par->data)
par->left=newnode(x);
else
par->right=newnode(x);
return root;
}
}
void display(struct node *root)
{
if(root==NULL)
return;
display(root->left);
printf("%d\t",root->data);
display(root->right);
}
struct node* findlca(struct node *root,int a,int b)
{
if(root==NULL)
return NULL;
if(a>root->data&&b>root->data)
return findlca(root->right,a,b);
if(a<root->data&&b<root->data)
return findlca(root->left,a,b);
return root;
}
int max(int a,int b)
{
return (a>b?a:b);
}
int findmax(struct node *root,int k)
{
int mx=INT_MIN;
while(root->data!=k)
{
if(k<root->data)
{
mx=max(mx,root->data);
root=root->left;
}
else
{
mx=max(mx,root->data);
root=root->right;
}
}
return max(mx,k);
}
int main()
{
int x,a,b;
struct node *root=NULL;
while(1)
{
scanf("%d",&x);
if(x==-1)
break;
root=insert(root,x);
}
display(root);
printf("\n enter the value of a and b ");
scanf("%d%d",&a,&b);
struct node *lca=findlca(root,a,b);
int max1=findmax(lca,a);
int max2=findmax(lca,b);
printf("\n the maximum node in between is %d",max(max1,max2));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment