# My C solution with Time Limit Exceeded

• I kept getting Time Limited Exceeded with C code, not entirely sure why.

``````/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     struct TreeNode *left;
*     struct TreeNode *right;
* };
*/
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
double* averageOfLevels(struct TreeNode* root, int* returnSize) {
double *tree_avg = malloc(*returnSize * sizeof(double));
int c=0;
struct TreeNode *parent,*current;
if(!tree_avg || !root)
return 0;
parent = NULL;
current = root;
tree_avg[c++]=current->val;
while (current) {
if ((current->left) && (current->right)) {
tree_avg[c++] = (double)(((double)current->left->val + (double)current->right->val)/2);
parent = current;
current = current->left;
} else {
if(parent) {
current = parent->right;
if (!(current->left) && !(current->right))
current= 0;
}
}
//printf("%lf\n",tree_avg[c]);
}
*returnSize=c;
return tree_avg;
}
``````

• I didn't have a chance to dig into it other than a quick glance. The first problem I noticed is you are allocating space for `tree_avg` using the value of `*returnSize`, which is zero to start with, and I didn't see a call to `realloc()` to resize the `tree_avg` later when you start using it. I'm surprised that's not giving you other issues.

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