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.
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).