# Why is it a runtime error, although it isn't in Ideone: last executed input [1,2,3], [3,2,1]

• /**

• Definition for binary tree

• struct TreeNode {

• ``````int val;
``````
• ``````TreeNode *left;
``````
• ``````TreeNode *right;
``````
• ``````TreeNode(int x) : val(x), left(NULL), right(NULL) {}
``````
• };
*/
class Solution {
private:
int inorderSearch(vector<int> &inorder, int inStrt, int inEnd, int target) {
for(int i = inStrt ; i <= inEnd ; i++ ) {
if(inorder[i] == target)
return i ;
}
}

TreeNode *buildTreeUtil(vector<int> &preorder, vector<int> &inorder, int inStrt, int inEnd) {
static int preIndex = 0 ;
if(inStrt > inEnd)
return NULL ;
TreeNode *root = new TreeNode(preorder[preIndex++]) ;
if(inStrt == inEnd)
return root ;
int inIndex = inorderSearch(inorder, inStrt, inEnd, root -> val ) ;
root -> left = buildTreeUtil(preorder, inorder, inStrt, inIndex - 1) ;
root -> right = buildTreeUtil(preorder, inorder, inIndex + 1 , inEnd) ;
return root ;
}

public:
TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
int inStrt = 0 ;
int inEnd = preorder.size() - 1 ;
TreeNode *root = NULL ;
root = buildTreeUtil(preorder, inorder, inStrt, inEnd) ;
return root ;
}
};

• this is the ideone link : http://ideone.com/RTITZd

• TreeNode *buildTreeUtil(vector<int> &preorder, vector<int> &inorder, int inStrt, int inEnd, int& preIndex) {
if(inStrt > inEnd)
return NULL ;
TreeNode *root = new TreeNode(preorder[preIndex++]) ;
if(inStrt == inEnd)
return root ;
int inIndex = inorderSearch(inorder, inStrt, inEnd, root -> val ) ;
root -> left = buildTreeUtil(preorder, inorder, inStrt, inIndex - 1, preIndex) ;
root -> right = buildTreeUtil(preorder, inorder, inIndex + 1 , inEnd, preIndex) ;
return root ;
}`enter code here`

• I read FAQ and tried without static variable,i tried "pass by reference" instead and it got accepted .

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