Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<bits/stdc++.h>
- using namespace std;
- struct node
- {
- int data;
- struct node* left;
- struct node* right;
- };
- typedef struct node Node;
- Node* create_node(int item)
- {
- Node* new_node=new Node();
- if(new_node==NULL)
- cout<<"Error"<<endl;
- else
- {
- new_node->data=item;
- new_node->left=new_node->right=NULL;
- }
- return new_node;
- }
- Node* insert_key(Node* x,int key)
- {
- Node* new_node=create_node(key);
- if(x==NULL)
- return new_node;
- if(key>x->data)
- x->right=insert_key(x->right,key);
- else if(key<x->data)
- x->left=insert_key(x->left,key);
- return x;
- }
- int maxpath(Node *q, int x)
- {
- Node *p=q;
- int mx=INT_MIN;
- while(p->data!=x)
- {
- if(p->data>x)
- {
- mx=max(mx,p->data);
- p=p->left;
- }
- else
- {
- mx=max(mx,p->data);
- p=p->right;
- }
- }
- return max(mx,x);
- }
- Node* lca(Node* root, int x, int y)
- {
- if(root == NULL)
- return NULL;
- if(root->data>x && root->data>y)
- return lca(root->left,x,y);
- if(root->data<x && root->data<y)
- return lca(root->right,x,y);
- return root;
- }
- int maxelement(Node* root,int x,int y)
- {
- Node *p;
- p=lca(root,x,y);
- return max(maxpath(p,x),maxpath(p,y));
- }
- int main()
- {
- Node* root=NULL;
- while(1)
- {
- int n;
- cin>>n;
- if(n!=-1)
- root=insert_key(root,n);
- else
- break;
- }
- int n;
- cin>>n;
- while(n--)
- {
- int x,y;
- cin>>x>>y;
- cout<<maxelement(root,x,y)<<endl;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment