# Run Time Error when using the recursion

• My solution is here. But I don't understand why it has run time error at the case [-1,0,1,3]. Thanks!

``````class Solution {
public:
TreeNode *sortedArrayToBST(vector<int> &num) {
int n = num.size();
if(n == 0) return NULL;
if(n == 1) return new TreeNode(num.at(0));
TreeNode *root;
root->val = num.at(n/2);

vector<int> v_left,v_right;
for(int i= 0; i< n;i++ ){
if(i<n/2) v_left.push_back(num.at(i));
if(i>n/2) v_right.push_back(num.at(i));
}
root->left  = sortedArrayToBST(v_left);
root->right = sortedArrayToBST(v_right);
return root;
}
};``````

• problem in code section

``````     TreeNode *root;
root->val = num.at(n/2);
``````

what about left and right pointer of root.. this is causing problem try this

TreeNode *root = new Treenode(num.at(n/2));

• Thank you so much!

• ``````public class Solution {
public TreeNode createTree(int[] num, int l, int r){
if(l>r) return null;
int mid=(r+l)/2;
TreeNode root = new TreeNode(num[mid]);
if(l!=r) {
root.left = createTree(num,l,mid-1);
root.right = createTree(num,mid+1,r);
}
return root;
}
public TreeNode sortedArrayToBST(int[] num) {
return createTree(num, 0, num.length-1);
}}``````

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