# Can anybody help me to figure out what is wrong with my code? Thanks a lot

• ``````class Solution {
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {

if(preorder.size() == 0)
return NULL;
int prePos = 0;
return helper(preorder, inorder, 0, inorder.size(), prePos);
}

TreeNode* helper(vector<int>& preorder, vector<int>& inorder, int start, int end, int &preind){
if(start >= end || preind >= preorder.size()){
preind--;
return NULL;
}

TreeNode* root = new TreeNode(preorder[preind]);
auto f = find(inorder.begin() + start, inorder.begin() + end, root->val);
int ind = f - inorder.begin();
root->left = helper(preorder, inorder, 0, ind, ++preind);
root->right = helper(preorder, inorder, ind + 1, end, ++preind);
return root;
}
};``````

• Here
root->left = helper(preorder, inorder, 0, ind, ++preind);
root->right = helper(preorder, inorder, ind + 1, end, ++preind);

you pass to the left preind+1 and to the right preind+2 but preind+2 is index of the second left child.

Example:

``````         1
2       3
4
``````

preorder 1 2 4 3

In first time you call indx 1 and indx 2 (for preind )but should 1 and 3

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