-
Notifications
You must be signed in to change notification settings - Fork 22
/
diagonal sum in binary tree
54 lines (45 loc) · 1.44 KB
/
diagonal sum in binary tree
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
/*
Consider lines of slope -1 passing between nodes (dotted lines in below diagram). The diagonal sum in a binary tree is the sum of all
node’s data lying between these lines. Given a Binary Tree, print all diagonal sums.
Note:The Input/Ouput format and Example given are used for system's internal purpose, and should be used by a user for Expected Output
only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function
specified, and not to write the full code.
Input:
The first line consists of T test cases. The first line of every test case consists of N, denoting the number of edges in the tree. The
second and third line of every test case consists of N, nodes of the binary tree.
Output:
Print space separated integers which are the diagonal sums for every diagonal present in the tree with slope -1.
Constraints:
1<=T<=100
1<=N<=100
Example:
Input:
2
3
4 1 L 4 3 R 3 3 L
5
10 8 L 10 2 R 8 3 L 8 5 R 2 2 L
Output:
7 4
12 15 3
*/
void getDiagonal(Node *root, map<int, vector<int>> &m, int d){
if(!root) return;
m[d].push_back(root->data);
getDiagonal(root->left,m,d+1);
getDiagonal(root->right,m,d);
}
void diagonalSum(Node* root)
{
map<int, vector<int>> m;
int d=0;
getDiagonal(root,m,d);
for(auto u: m){
int sum=0;
for(int it=0; it<u.second.size(); it++){
sum = sum + u.second[it];
}
cout<<sum<<" ";
}
cout<<'\n';
}