Least Common Ancestor
#include "iostream"
using namespace std;
class LcaClass
{
struct Node
{
int data;
Node* left;
Node* right;
};
Node* root;
public:
LcaClass()
{
root = NULL;
}
void insert(int data);
int lca(int first, int second);
};
void LcaClass::insert(int data)
{
Node* current = new Node;
current->data = data;
current->left = NULL;
current->right = NULL;
Node* parent = root;
Node* temp = NULL;
if(parent == NULL)
{
root = current;
parent = root;
}
else
{
while(parent)
{
temp = parent;
if(data > parent->data)
{
parent = parent->right;
}
else
{
parent = parent->left;
}
}
if(temp->data > data)
{
temp->left = current;
}
else
{
temp->right = current;
}
}
}
int LcaClass::lca(int firstvalue,int secondvalue)
{
if(root == NULL)
{
cout<<"root value is NULL"< return 0;
}
while(root)
{
if(root->data > firstvalue && root->data > secondvalue)
{
root = root->left;
}
else if(root->data <= firstvalue && root->data <= secondvalue)
{
root = root->right;
}
else if(root)
{
return root->data;
}
}
}
int main()
{
LcaClass lcaClass;
int data = 0;
char ch = 'y';
int first = 0;
int second = 0;
while(ch=='y')
{
cout<<"Enter the input values"< cin>>data;
lcaClass.insert(data);
cout<<"For entering the further values press 'y'"< cin>>ch;
}
cout<<"Enter the first value"< cin>>first;
cout<<"Enter the second value"< cin>>second;
int check = lcaClass.lca(first,second);
cout<<"Least Common Ancestor value is: "< cin>>ch;
}
using namespace std;
class LcaClass
{
struct Node
{
int data;
Node* left;
Node* right;
};
Node* root;
public:
LcaClass()
{
root = NULL;
}
void insert(int data);
int lca(int first, int second);
};
void LcaClass::insert(int data)
{
Node* current = new Node;
current->data = data;
current->left = NULL;
current->right = NULL;
Node* parent = root;
Node* temp = NULL;
if(parent == NULL)
{
root = current;
parent = root;
}
else
{
while(parent)
{
temp = parent;
if(data > parent->data)
{
parent = parent->right;
}
else
{
parent = parent->left;
}
}
if(temp->data > data)
{
temp->left = current;
}
else
{
temp->right = current;
}
}
}
int LcaClass::lca(int firstvalue,int secondvalue)
{
if(root == NULL)
{
cout<<"root value is NULL"<
}
while(root)
{
if(root->data > firstvalue && root->data > secondvalue)
{
root = root->left;
}
else if(root->data <= firstvalue && root->data <= secondvalue)
{
root = root->right;
}
else if(root)
{
return root->data;
}
}
}
int main()
{
LcaClass lcaClass;
int data = 0;
char ch = 'y';
int first = 0;
int second = 0;
while(ch=='y')
{
cout<<"Enter the input values"<
lcaClass.insert(data);
cout<<"For entering the further values press 'y'"<
}
cout<<"Enter the first value"<
cout<<"Enter the second value"<
int check = lcaClass.lca(first,second);
cout<<"Least Common Ancestor value is: "<
}
Comments
Post a Comment