Tress find sum at level K

some of my test cases are not working thogh its giving correct answer to the custom inputs

hi @kshitiz_joshi try printing sum variable instead ot the return value of the function

but why its showing pronblem in returning the answer i was not able to get a way to simply prin the value it starts printing 3 times
void levelsum(node *root,int k,int &sum)

{

if(k==0)

{sum=sum+root->data;

return ;}

levelsum(root->left,k-1,sum);

levelsum(root->right,k-1,sum);

cout<<sum<<endl;

}

@kshitiz_joshi print it in main function na why would it print 3 times? Call the sum function and print the value of sum variable AFTER it has been called

ohh got you, but still 3 test cases are wrong showing run error
levelsum(root,k,sum);

cout<<sum; you are talking about this n

@kshitiz_joshi yeah i am saying like this…is this showing error?

yaa run time error for 3 test cases

@kshitiz_joshi i’ll check, wait

@kshitiz_joshi in your constructor, make left = NULL, you made a typo
image

ok done that too but still 3 test cases are wrong

@kshitiz_joshi can you share the code with all the changes?

hi @kshitiz_joshi add one more base case, if root == NULL, return 0

1 Like

ohh thanks a lot and why did this happen can you explain that too k should be hitting zero before the null n?

@kshitiz_joshi it may be the case that not all levels are full, so k > 0 but the node may not be there

1 Like

mam please solve this doubt too i am getting about 2 TLE test cases and 9 test cases are correct

hi @kshitiz_joshi this doubt has been taken by another TA it will be resolved soon. Happy Learning!

should i post it again so that someone else handle it?he is not answering

@kshitiz_joshi re-open the doubt if they dont answer within 24 hours, but please have some patience.