Run Time Error when using the recursion


  • 1
    Y

    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;
        }
    };

  • 1
    D

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


  • 0
    Y

    Thank you so much!


  • 4
    J
    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.