Easy to understand solution


#1

/**

  • Definition for binary tree
  • struct TreeNode {
  • int val;
    
  • TreeNode *left;
    
  • TreeNode *right;
    
  • TreeNode(int x) : val(x), left(NULL), right(NULL) {}
    
  • };
    */

bool both(TreeNode* root , int a)
{bool right = false, left = false;
if(root->val==a)
return true;

 if(root->left==NULL&&root->right==NULL)
 return false;
 if(root->left)
  left = both(root->left, a);
 if(root->right)
  right = both(root->right, a);
 return left||right;

}

TreeNode* findlca(TreeNode* root, int a, int b)
{
if(root==NULL)
return NULL;

 if(root->val==a||root->val==b)
 {
     return root;
 }

TreeNode* left = findlca(root->left, a,b);
TreeNode* right = findlca(root->right, a,b);

if(left&&right)
return root;
else if(left)
return left;

else if(right)
return right;



 }

int Solution::lca(TreeNode* A, int B, int C) {

bool k1 = both(A,B);
bool k2 = both(A,C);
if(k1&&k2)
{TreeNode* ans = findlca(A,B,C);
return ans->val;}

else
return -1;
}