C++ recursive solution preorder


#1

bool preOrder(TreeNode* A, vector& path,int target){
if(A == NULL){
return false;
}

path.push_back(A->val);

if(A->val == target){
    return true;
}

if(preOrder(A->left,path,target) || preOrder(A->right,path,target)){
    return true;
}

path.pop_back();
return false;

}
int Solution::lca(TreeNode* A, int B, int C) {
vector vecB,vecC;

preOrder(A,vecB,B);
preOrder(A,vecC,C);

if(vecB.empty() || vecC.empty()) return -1;

for(int i = vecB.size() - 1; i >= 0; i--){
    for(int j  = vecC.size() - 1; j >= 0; j--){
        if(vecC[j] == vecB[i])
            return vecC[j];
    }
}
return -1;

}