Problem: https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
My Solution:
TreeNode* func(vector<int>& preorder, int startIndex, map<int, int> mp, int i, int j)
{
if(i>j)
return NULL;
TreeNode* root=new TreeNode(preorder[startIndex]);
int ind=mp[preorder[startIndex]];
startIndex++;
root->left=func(preorder, startIndex, mp, i, ind-1);
root->right=func(preorder, startIndex, mp, ind+1, j);
return root;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
map<int, int> mp;
for(int i=0;i<inorder.size();i++)
{
mp[inorder[i]]=i;
}
int startIndex=0;
return func(preorder, startIndex, mp, 0, inorder.size()-1);
}This is the solution considering the general approach of getting the root from preorder vector and getting the left and the right subtrees from the inorder vector. This gives Heap buffer overflow, I tried the following possible solutions:
I incremented the startIndex using startIndex++ as done above
I passed (did the recursive call) using startIndex+1.
Both these solutions give heap overflow. The working solution for this is when the startIndex is defined in the function definition as int& startIndex. Can someone explain why not passing startIndex by reference is giving heap overflow?