Tree Traversal once - Efficient solution


#1

int sol(TreeNode* A, int B, int C,bool &b1,bool &b2){
int ans=0;
if(A==NULL) return 0;
if(A->val==B) {ans+=B;b1=true;}
if(A->val==C) {ans+=C;b2=true;}
ans+=sol(A->left,B,C,b1,b2)+sol(A->right,B,C,b1,b2);
if(ans==B+C) return A->val;
return ans;
}

int Solution::lca(TreeNode* A, int B, int C){
bool found1=false,found2=false;
int ans=sol(A,B,C,found1,found2);
if(found1&&found2) return ans;
return -1;
}