-
Notifications
You must be signed in to change notification settings - Fork 2
/
sumrootlevelwise.cpp
76 lines (71 loc) · 1.62 KB
/
sumrootlevelwise.cpp
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include <iostream>
#include <queue>
using namespace std;
//define node via class for tree
class Node{
public:
int data;
Node *right;
Node *left;
Node(){
right=NULL;
left=NULL;
}
Node(int n){
data=n;
right=NULL;
left=NULL;
}
};
Node *root=NULL;
//function to create tree
Node* createTree(Node *node=NULL){
int data;
cout << "Enter number (Enter -1 to stop creation) : ";
cin >> data;
if(data==-1){
return NULL;
}else{
cout << "Enter data at left node : ";
Node* tmp=new Node(data);
tmp->left=createTree();
cout << "Enter data at right node : ";
tmp->right=createTree();
return tmp;
}
}
//function to print the sum of leaf node at each level
void printLevelLeafSum(){
queue<pair<Node*,int>> qu;
Node *tmp;
int sum{0};
int lvl{1};
if(root==NULL){
cout << sum;
}else{
qu.push({root,lvl});
while(!qu.empty()){
tmp=qu.front().first;
if(lvl!=qu.front().second){
cout << sum << endl;
sum=0;
}
lvl=qu.front().second;
if(tmp->right==NULL && tmp->left==NULL){
sum+=tmp->data;
}else{
if(tmp->left!=NULL) qu.push({tmp->left,lvl+1});
if(tmp->right!=NULL) qu.push({tmp->right,lvl+1});
}
qu.pop();
}
cout << sum << endl;
}
}
int main(int argc, const char * argv[]) {
root=createTree();
cout << "\n";
printLevelLeafSum();
cout << "\n";
return 0;
}