C++ recursive solution || simple and efficient


#1
TreeNode* construction(int pre_s,int pre_e,int in_s, int in_e, vector<int>& pre, vector<int>& in){

if(in_s > in_e)
    return NULL;

TreeNode* node = new TreeNode(pre[pre_s]);
   

int k = 0;

for(int i = in_s ; i <= in_e ; i++){
    if(in[i] == pre[pre_s]){
        k = i;
    }    
}

  
node->left  = construction(pre_s+1,pre_s+k-in_s,in_s,k-1,pre,in);
node->right = construction(pre_s+k-in_s+1,pre_e,k+1,in_e,pre,in);
   
   return node;
}

 
TreeNode* Solution::buildTree(vector<int> &A, vector<int> &B) {
int pre_s,pre_e,in_s,in_e;
pre_s = 0;
pre_e = A.size() - 1;
in_s = 0;
in_e = B.size() - 1;

TreeNode* node = construction(pre_s,pre_e,in_s,in_e,A,B);
return node;
}