I got different result comparing with my local compiler


  • 0
    C

    I got a wrong answer when I submit my code on OJ, it says:

    Input:	[1,2], [1,2]
    Output:	{1}
    Expected:	{1,#,2}
    

    But on my local machine, with codeblocks, it gets exactly the expected answer. I am wondering what is wrong with my code? Is anyone encountered with the same problem?

    class Solution {
    public:
        TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
            if(preorder.size()<1||inorder.size()<1)
                return NULL;
            if(preorder.size()!=inorder.size())
                return NULL;
            if(preorder.size()==1)
                return new TreeNode(preorder[0]);
            
            unordered_map<int,int> mp;
            mp.clear();
            for(int i=0;i<inorder.size();i++)
                mp[inorder[i]]=i;
            TreeNode* root=new TreeNode(preorder[0]);
            //for(int i=1;i<preorder.size();i++)
            build(root, preorder, inorder, mp);
            return root;
        }
        
        void build(TreeNode* &root, vector<int> &preorder, vector<int>& inorder, unordered_map<int,int> &mp){
            static int id=1;
            
            if(id>=inorder.size()) return;
            //Nodes without left and right 
            if(mp[root->val]==0){
                if(mp.find(inorder[mp[root->val]+1])==mp.end()){
                    //mp.erase(root->val);
                    return;
                }
            }else if(mp[root->val]==inorder.size()-1){
                if(mp.find(inorder[mp[root->val]-1])==mp.end()){
                    //mp.erase(root->val);
                    return;
                }
            }else if(mp.find(inorder[mp[root->val]-1])==mp.end()&&mp.find(inorder[mp[root->val]+1])==mp.end()){
                //mp.erase(root->val);
                return;    
            }
            
            int ind=mp[root->val];
            mp.erase(root->val);
            if(mp[preorder[id]]<ind){
                if(root->left==NULL){
                    root->left=new TreeNode(preorder[id]);
                    id++;
                    build(root->left,preorder,inorder,mp);
                }
            }
            if(id>=inorder.size()) return;
            if(mp[preorder[id]]>ind){
                if(root->right==NULL){
                    root->right=new TreeNode(preorder[id]);
                    id++;
                    build(root->right,preorder,inorder,mp);
                }
            }
            return;
        }
    };

  • 0
    F

    yeah ! i got same problems


  • 0
    C

    What I now know is the keyword "static" is problematic in OJ. In my case, I changed the static statement and solved this problem.


Log in to reply
 

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