Sum at K level Not able to obtain correct answer

I am not able to obtain the answer. Can anyone please indicate/guide me on how to obtain the correct answer

@seshanarayanan12
Your build tree function is wrong. Make these changes.

if(n==0){
return root;
}
if(n>=1){
root->left=build(root->left);
}
if(n==2){
root->right=build(root->right);
}
return root;

1 Like

Thank You sir. If you could also explain the if (n>=1) condition…

@seshanarayanan12
The condition n>=1 is for the cases when we get input 2 basically. When we are given that the current node has 2 children , first we need to take the input for its left child and then the right child. In your code , you have implemented condition for n==2 and made the right child in it. And that is the problem , you only created the right child. In this case we wish to have the body for creation of left child to be executed first and then the right child part as well. Hence in case there is one or more one child , we first make the left child in both the cases . Hence n>=1.

1 Like

Thank You for the explanation sir!!