# Sharing my 36ms C++ solution

• ``````/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
private:
TreeNode* buildTreeHelper(vector<int>& preorder, vector<int>& inorder, int prf, int prl, int inf, int inl)
{
if(prf>prl)
return NULL;
int midvalue = preorder[prf];
TreeNode* tree = new TreeNode(midvalue);
int i, shift;
for(i=0; i<=inl-inf; i++)
{
if(midvalue == inorder[inf+i])
{
shift = i;
break;
}
}

tree->left  = buildTreeHelper(preorder, inorder, prf+1, prf+shift, inf, inf+shift-1);
tree->right = buildTreeHelper(preorder, inorder, prf+shift+1, prl, inf+shift+1, inl);
return tree;
}
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
int np = preorder.size();
int ni = inorder.size();
return buildTreeHelper(preorder, inorder, 0, np-1, 0, ni-1);
}
};``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.