C++ solution for this problem


#1

void preorder(TreeNode* root,int data,bool &state)
{
if(root==NULL)
{
return ;
}
if(root->val==data)
{
state=true;
return;
}
preorder(root->left,data,state);
preorder(root->right,data,state);
}
int LCancestor(TreeNode* root,int B,int C)
{
if(root==NULL)
{
return 0;
}
if(root->val==B || root->val==C)
{
return root->val;
}
int left=LCancestor(root->left,B,C);
int right=LCancestor(root->right,B,C);
if(left!=0 && right!=0)
{
return root->val;
}
else
{
if(left==0)
{
return right;
}
else
{
return left;
}
}
}
int Solution::lca(TreeNode* root, int B, int C) {
bool state1=false;
bool state2=false;
preorder(root,B,state1);
preorder(root,C,state2);
if(!state1 || !state2)
{
return -1;
}
int result=LCancestor(root,B,C);
return result;
}