Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

TLE in C but not in C++

I was trying to solve this question on LeetCode.

This is my solution, which gets TLE (Time Limit Error):

int height(struct TreeNode*root)
{
    if(!root)
    return 0;

    return(height(root->left) > height(root->right) ? height(root->left) : height(root->right) )+1;
}
int traverse(struct TreeNode *root, int level, int *ans)
{
    if(!root)
    return *ans;
    
    if(level == 1)
    (*ans) = (*ans) + root->val;

    traverse(root->left,level-1,ans);
    traverse(root->right,level-1,ans);

    return *ans;
}
int deepestLeavesSum(struct TreeNode* root){

    int ht = height(root); 
    int ans = 0; 
    
    return traverse(root,ht,&ans);
    
}

And here is a similar implementation in C++ which doesn’t get TLE, in fact it runs very fast.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class Solution {
public:
    int height (TreeNode* root)
    {
        if (!root)
            return 0;
        return max(height(root->left), height(root->right)) + 1;
    }
    int sum = 0;
    int sum_at_k(TreeNode* root, int k)
    {
        
        if (!root)
            return sum;
        if (k == 0)
            sum = sum + root->val;
        sum_at_k(root->left, k - 1);
        sum_at_k(root->right, k - 1);
        return sum;
    }
    
    int deepestLeavesSum(TreeNode* root) 
    {
        int h = height(root);
        int sum = sum_at_k(root, h - 1);
        return sum;
    }
};

Why is it happening?

>Solution :

You used max in your C++ implementation, but the version of max in your C version calls height more often than necessary (calling it for each subtree to decide between subtrees, and then calls it again to get the value to return).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading