Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- using namespace std;
- class Node{
- public:
- int data;
- Node *left,*right;
- Node(int key){
- data=key;
- left=right=NULL;
- }
- };
- Node* FindLCA(Node* root,Node* first,Node* second ){
- if(root==NULL)
- return NULL;
- if((min(first->data,second->data)<root->data && max(first->data,second->data)>root->data) ||first->data==root->data||second->data==root->data)
- return root;
- if(first->data<root->data )
- return FindLCA(root->left,first,second);
- if(first->data>root->data)
- return FindLCA(root->right,first,second);
- }
- void Print(Node* root,int first,int last){
- if(root==NULL)
- return;
- if(first<root->data)
- Print(root->left,first,last);
- if(root->data>=first && root->data<=last)
- cout<<" "<<root->data;
- if(root->data<last)
- Print(root->right,first,last);
- }
- void Insert(Node **root_ref,int key){
- if(*root_ref==NULL){
- *root_ref=new Node(key);
- return;
- }
- if((*root_ref)->data<key)
- Insert(&((*root_ref)->right),key);
- else
- if((*root_ref)->data>key)
- Insert(&((*root_ref)->left),key);
- }
- int main(){
- Node *root=NULL;
- Insert(&root,5);
- Insert(&root,7);
- Insert(&root,6);
- Insert(&root,2);
- Insert(&root,8);
- Node* temp=FindLCA(root,(root->right)->left,(root->right)->right);
- if(temp)
- cout<<temp->data;
- else
- cout<<"values are not correct";
- return 0;
- }
Add Comment
Please, Sign In to add comment