If any node doesn’t have a child I am taking -1 as an input.But how to take input in this one?
How to input the data in tree?
#include
using namespace std;
int sum=0;
class node{
public:
int data;
node* left;
node* right;
node(int d)
{
data=d;
left=NULL;
right=NULL;
}
};
node* buildTree()
{
int d;
cin>>d;
if(d==-1)
return NULL;
node* f=new node(d);
f->left=buildTree();
f->right=buildTree();
return f;
}
void sumKthLevel(node* root,int k)
{
if(root==NULL)
return;
if(k==1)
{
sum=sum+root->data;
return;
}
sumKthLevel(root->left,k-1);
sumKthLevel(root->right,k-1);
}
int main()
{
node* root=buildTree();
int k;
sumKthLevel(root,k);
cout<<sum<<endl;
return 0;
}
que: sum at level k
problem:time limit exceeded
make a generic tree u are creating a binary tree thats why tle is coming
Hey Meghna, as you are not responding to this thread, I am marking your doubt as Resolved for now. Re-open it if required.
Please mark your doubts as resolved in your course’s “ Ask Doubt ” section, when your doubt is resolved.