Run Time Error when using the recursion

  • 1

    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 {
        TreeNode *sortedArrayToBST(vector<int> &num) {
            int n = num.size();
            if(n == 0) return NULL;
            if(n == 1) return new TreeNode(;
            TreeNode *root;
            root->val =;
            vector<int> v_left,v_right;
            for(int i= 0; i< n;i++ ){
                if(i<n/2) v_left.push_back(;
                if(i>n/2) v_right.push_back(;
            root->left  = sortedArrayToBST(v_left);
            root->right = sortedArrayToBST(v_right);
            return root;

  • 1

    problem in code section

         TreeNode *root;
        root->val =;

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

    TreeNode *root = new Treenode(;

  • 0

    Thank you so much!

  • 4
    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);

Log in to reply

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