I am getting runtime error for [1,2,3,4],[1,2,3,4], although it's perfect in my compiler.


  • 0
    G
    class Solution {
    public:
        int search(vector<int> &inorder,int low,int high,int target)
        {
            int i=0;
            for(i=low;i<=high;i++)
            {
                if(inorder[i]==target)
                    return i;
            }
        }
        TreeNode* prein(vector<int> &preorder,vector<int> &inorder,int ilow,int ihigh)
        {
            static int preindex=0;
            if(ilow>ihigh)
                return NULL;
            TreeNode *root=new TreeNode(preorder[preindex]);
            preindex++;
            if(ilow==ihigh)
                return root;
            int inindex=search(inorder,ilow,ihigh,root->val);
            root->right=prein(preorder,inorder,inindex+1,ihigh);
            root->left=prein(preorder,inorder,ilow,inindex-1);
            return root;
        }
        TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
            int p1=preorder.size();
            int i1=inorder.size();
            if(p1==0 && i1==0)
                return NULL;
                
            return prein(preorder,inorder,0,i1-1);
            
        }
    };

  • 0
    M

    There seems to be an issue with the statement
    if(ilow == ihigh) --> this leads to self loops right


  • 0
    G

    if its the last element in inorder vector then we dont need to check for its subtrees so hows does it leads to self loop


  • 4
    S

    The problem comes from your static int preindex = 0.

    OJ will run all test case by running program only once, so your static variable will grow large during the entire process.

    However, there is another bug in your code, would also bring to Runtime Error.

        root->right=prein(preorder,inorder,inindex+1,ihigh);
        root->left=prein(preorder,inorder,ilow,inindex-1);
    

    You should swap their order, first left then right.


  • 0
    N

    Then how to sort out static int preindex = 0 runtime error ?


  • 0
    D

    Just pass preindex through the argument I guess.


Log in to reply
 

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