int found_or_not = -1;
int dfs(TreeNode* A, int B, int C){
if(found_or_not > 0){ // if lca is found
return 0;
}
if(!A){ // NULL case
return 0;
}
if(A->val == B && A->val == C){ // lca is A->val if "B == C == A->val"
found_or_not = A->val;
return 0;
}
int l = dfs(A->left, B, C);
int r = dfs(A->right, B, C);
if(A->val == B || A->val == C){ // if lca is any one of B || C
if(l || r){ // one among B |`Preformatted text`| C is already detected
found_or_not = A->val;
return 0;
}
return 1;
}if(l & r){ // if lca is not any one of B || C
found_or_not = A->val;
return 0;
}
return l || r; // any one value found or not case
}
int Solution::lca(TreeNode* A, int B, int C) {
found_or_not = -1; // reset value for multiple test cases
dfs(A, B, C);
return found_or_not;
}