Why my code need 740ms?


  • 0
    T
    TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) 
    {
    
      TreeNode * n=NULL;
      if(preorder.size()==0)
        return n;
      n =  new TreeNode(0);
      n->val=preorder[0];
    
      if(preorder.size()==1)
      {
        n->right= NULL;
        n->left = NULL;
        return n;
      }
    
    
      std::vector<int>::iterator first = std::find(inorder.begin(), inorder.end(), preorder[0]);
      vector<int> lTreeInOrder;
      vector<int> rTreeInOrder;
      std::copy(inorder.begin(), first, std::back_inserter(lTreeInOrder));
      std::copy(first+1, inorder.end(), std::back_inserter(rTreeInOrder));
      int lenLTree= lTreeInOrder.size();
    
      inorder.clear();
      inorder.shrink_to_fit();
    
    
      vector<int> lTreePrOrder;
      vector<int> rTreePrOrder;
      std::copy(preorder.begin()+1, preorder.begin()+lenLTree+1, std::back_inserter(lTreePrOrder));
      std::copy(preorder.begin()+lenLTree+1, preorder.end(), std::back_inserter(rTreePrOrder));  
    
      preorder.clear();
      preorder.shrink_to_fit();
    
    
      n->left = buildTree(lTreePrOrder,lTreeInOrder);
      n->right = buildTree(rTreePrOrder,rTreeInOrder); 
    
      return n;
    
    
    }

Log in to reply
 

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