-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathFind Sum at Level K
More file actions
58 lines (48 loc) · 860 Bytes
/
Find Sum at Level K
File metadata and controls
58 lines (48 loc) · 860 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include<bits/stdc++.h>
using namespace std;
class node{
public:
int data;
node* left;
node* right;
node(int d){
data = d;
left = right = NULL;
}
};
node* buildTree(){
int d,c;
cin>>d>>c;
node* root = new node(d);
if(c==0)
{
}
else if(c==1)
{
root->left = buildTree();
}
else if(c==2)
{
root->left = buildTree();
root->right = buildTree();
}
return root;
}
void findSum(node* root , int k, int &sum){
if(root==NULL)
return;
if(k==0){
sum += root->data;
return;
}
findSum(root->left,k-1,sum);
findSum(root->right,k-1,sum);
}
int main(){
node* root = buildTree();
int k;
cin>>k;
int sum=0;
findSum(root,k,sum);
cout<<sum;
}