Time Limit Exceeded with O(nlogn).Help Anyone ?


  • 0
    T

    Can anyone explain why it is giving TLE?

    class Solution {
    public:
        TreeNode *newnode(int v) {
            TreeNode *temp = (TreeNode *)malloc(sizeof(TreeNode));
            temp->val = v;
            temp->left = temp->right = nullptr;
            return temp;
        }
       TreeNode *insert(TreeNode *root, int num, map <int,int> pos) {
            if(!root) return newnode(num);
            if(pos[num] < pos[root->val])
                root->left = insert(root->left,num,pos);
            else
                root->right = insert(root->right,num,pos);
           
           return root;
        }
        
        TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
            if(!nums.size()) return nullptr;
            map <int,int> pos;
            for(int i=0;i<nums.size();++i) {
                pos[nums[i]]=i+1;
            }
            sort(nums.begin(),nums.end());
            reverse(nums.begin(),nums.end());
            TreeNode *root = newnode(nums[0]);
            for(int i=1;i<nums.size();++i) {
                root = insert(root,nums[i],pos);
            } 
            return root;
        }
    };
    

Log in to reply
 

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