Easy C++ recursive solution with comments


#1
 int found;
 // this function finds the path of the given node from the root and stores it in vector v
 void pathfinder(TreeNode *root, int search,vector <int> &v)
 {
    if(root==NULL)
    return;
    if(search==root->val)
    found=true;
    if(found==false)
    pathfinder(root->left, search,v);
    if(found==false)
    pathfinder(root->right,search,v);
    if(found==true)
    v.push_back(root->val);
 }
 
int Solution::lca(TreeNode* root, int search1, int search2) {
    vector<int> v1,v2;
    found=false;
    pathfinder(root, search1,v1);   //get path of search1 from root
    found=false;
    pathfinder(root, search2,v2);   //get path of search 2 from root
    
    for(int i=0;i<v1.size();i++)
    {
        for(int j=0;j<v2.size();j++)
        {
            //if the values of path match then return the value
            if(v1[i]==v2[j])    
            return v1[i];
        }
    }
    return -1;
}