Skip to content

Commit 7bbe662

Browse files
authored
Sum At Level K
1 parent 72c85b8 commit 7bbe662

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed

Hacker Blocks/Sum At Level K.cpp

+83
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
/* Hacker Blocks */
2+
/* Title - Find Sum At Level K - Trees */
3+
/* Created By - Akash Modak */
4+
/* Date - 27/08/2020 */
5+
6+
// Take input of a generic tree using buildtree() function and also take input K the level at which we need to find the sum.
7+
8+
// Input Format
9+
// Take a generic tree input where you are first given the data of the node and then its no of children. The input is of preorder form and it is assured that the no of children will not exceed 2. The input of the tree is followed by a single integer K.
10+
11+
// Constraints
12+
// 1 <= Nodes in tree <=1000
13+
// 1<K<10
14+
15+
// Output Format
16+
// A single line containing the sum at level K.
17+
18+
// Sample Input
19+
// 1 2
20+
// 2 2
21+
// 3 0
22+
// 4 0
23+
// 5 2
24+
// 6 0
25+
// 7 0
26+
// 2
27+
// Sample Output
28+
// 20
29+
// Explanation
30+
// Here the tree looks like
31+
32+
// 1 Level 0
33+
// / \
34+
// 2 5 Level 1
35+
// / \ / \
36+
// 3 4 6 7 Level 2
37+
// Sum at Level 2 = 3 + 4 + 6 + 7 = 20
38+
39+
40+
#include<bits/stdc++.h>
41+
using namespace std;
42+
class node{
43+
public:
44+
int data;
45+
node *left,*right;
46+
node(int d){
47+
data=d;
48+
left=NULL;
49+
right=NULL;
50+
}
51+
};
52+
int sum=0;
53+
node* buildTree(){
54+
int data,num;
55+
cin>>data>>num;
56+
node* root = new node(data);
57+
if(num==2){
58+
root->left=buildTree();
59+
root->right=buildTree();
60+
}
61+
if(num==1)
62+
root->left=buildTree();
63+
64+
return root;
65+
}
66+
void kthsum(node* root,int level,int k){
67+
if(root==NULL)
68+
return ;
69+
if(level==k){
70+
sum+=root->data;
71+
return ;
72+
}
73+
kthsum(root->left,level+1,k);
74+
kthsum(root->right,level+1,k);
75+
}
76+
int main() {
77+
node* root = buildTree();
78+
int k;
79+
cin>>k;
80+
kthsum(root,0,k);
81+
cout<<sum<<endl;
82+
return 0;
83+
}

0 commit comments

Comments
 (0)