getting wrong answer
I haven’t handled the case for 1 child
my doubt is, when node has 1 child how do we know that it is left or right child ?
and how to implement it ?
Find sum at level k
Is your code failing all test cases ? .
no
3 out of 4 failed, 1 passing
I think ur not building the tree correctly. What about the NULL values after leaves … where have you appointed the NULL values.
it gets initialized when new node is made, in node class I have initialized left and right child as NULL
Done
Just made a little changes please check. Since the input is given in preorder form, then it means that if a node has 1 child it has got to be the left one.
#include<iostream>
using namespace std;
class node {
public:
int data;
node*left;
node*right;
node(int d):data(d),left(NULL),right(NULL) {}
};
node* build() {
pair<int,int> p;
cin>>p.first>>p.second;
node* root=new node(p.first);
if(p.second) {
if(p.second>=1)
root->left=build();
if(p.second>=2)
root->right=build();
}
return root;
}
int sum=0;
void getSumAtLevelK(node*root,int k) {
if(root==NULL)return ;
if(k==0) {
sum+=root->data;
return;
}
getSumAtLevelK(root->left,k-1);
getSumAtLevelK(root->right,k-1);
}
int main() {
node*root=build();
int k;
cin>>k;
getSumAtLevelK(root,k);
cout<<sum<<"\n";
return 0;
}
Actually it doesnt matter if the node has only 1 child. You can make that either left or right. It doesn’t matter since we r dealing with levels only.
Please mark it resolved if ur doubt was cleared.
getting run error
I have added an extra condition please check the code more thoroughly 
If u feel ur doubt is resolved please rate ur experience.