Why Timeout? Complexity is O(n*logn).


  • 0
    R

    I can't figure out why timeout is happening.
    Kindly help me fix it.

    /**

    • Definition for a binary tree node.

    • struct TreeNode {

    • int val;
      
    • TreeNode *left;
      
    • TreeNode *right;
      
    • TreeNode(int x) : val(x), left(NULL), right(NULL) {}
      
    • };
      /
      map<int,int> ans;
      int maxval,minval;
      int sumIt(TreeNode
      root)
      {
      if(root==NULL)
      return 0;

      root->val+= sumIt(root->left)+ sumIt(root->right);
      maxval=max(maxval,root->val);
      minval=min(minval,root->val);
      return root->val;
      }
      void printans(struct TreeNode* root)
      {
      if(root==NULL)
      return;

      printans(root->left);
      printans(root->right);

      if(ans.find(root->val)!=ans.end())
      ans[root->val]=ans[root->val]+1;
      else ans[root->val]=1;

    }
    class Solution {
    public:
    vector<int> findFrequentTreeSum(TreeNode* root) {
    maxval=INT_MIN , minval=INT_MAX;
    int a=sumIt(root);
    printans(root);
    int maxo=INT_MIN;
    for(int i=minval;i<=maxval;i++)
    {
    if(ans[i]>maxo)
    maxo=ans[i];
    }
    vector<int> v;
    for(int i=minval;i<=maxval;i++)
    if(ans[i]==maxo)
    v.push_back(i);

        ans.clear();
        return v;
    }
    

    };


Log in to reply
 

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