Recursive solution with proper functions in C++


#1

int searching( vector &inorder, int l, int h, int val ){

for( int i=l; i<=h; i++ ){
    
    if( val == inorder[i] )
        return i;
}

//return -1;

}

TreeNode* createTree( vector &inorder, vector &preorder, int low, int high, int *lastpos ){

if( low > high )
    return NULL;
    
TreeNode *node = new TreeNode( preorder[*lastpos] );
++(*lastpos);

int ind = searching( inorder, low, high, node->val );

node->left = createTree( inorder, preorder, low, ind-1, lastpos );
node->right = createTree( inorder, preorder, ind+1, high, lastpos );

return node;

}

TreeNode* Solution::buildTree(vector &A, vector &B) {

if( A.empty() || B.empty() )
    return NULL;

int is = A.size()-1;
int ps = 0;

return createTree( B, A, 0, is, &ps );

}