```
class Solution {
public:
TreeNode *LCA(TreeNode *root, int val1, int val2) {
if (!root) return NULL;
if (root->val == val1 || root->val == val2) return root;
TreeNode *L = LCA(root->left, val1, val2);
TreeNode *R = LCA(root->right, val1, val2);
if (L && R) return root; // If val1, val2 are on both sides
return L ? L : R; // either one of val1, val2 is on one side OR val1, val2 is not in L&R subtrees
}
bool find(TreeNode *root, int val1) {
if (!root) return false;
if (root->val == val1) return true;
return (find(root->left, val1) || find(root->right, val1));
}
int lca(TreeNode *root, int val1, int val2) {
if (!find(root, val1) || !find(root, val2)) return -1;
TreeNode *ans = LCA(root, val1, val2);
if (!ans) return -1;
return ans->val;
}
};
```
Doubt in editorial sol'n why do we need the "bool find" function?
Lets say that we have a tree
we use the above code,just not the find part
eg1-1 2 3 -1 -1 -1 -1
val1=1;
val2=3;
answer using the code without find is 1(root->val==val1),now lets take another example
eg2-1 2 -1 -1 -1
val1=1
val2=3
now root with data 3 is not present in our tree,but when we calculate the answer without find
it still returns 1(root->val==val1) without checking the second node is present or not;
answer should be -1(FIND helps us in tackling this problem)