This repository has been archived by the owner on Dec 28, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy pathDiagonal sum of Binary tree Solution
83 lines (66 loc) · 1.67 KB
/
Diagonal sum of Binary tree Solution
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
77
78
79
80
81
82
83
// C++ Program to find diagonal
// sum in a Binary Tree
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int data;
struct Node* left;
struct Node* right;
};
struct Node* newNode(int data)
{
struct Node* Node =
(struct Node*)malloc(sizeof(struct Node));
Node->data = data;
Node->left = Node->right = NULL;
return Node;
}
// root - root of the binary tree
// vd - vertical distance diagonally
// diagonalSum - map to store Diagonal
// Sum(Passed by Reference)
void diagonalSumUtil(struct Node* root,
int vd, map<int, int> &diagonalSum)
{
if(!root)
return;
diagonalSum[vd] += root->data;
// increase the vertical distance if left child
diagonalSumUtil(root->left, vd + 1, diagonalSum);
// vertical distance remains same for right child
diagonalSumUtil(root->right, vd, diagonalSum);
}
// Function to calculate diagonal
// sum of given binary tree
void diagonalSum(struct Node* root)
{
// create a map to store Diagonal Sum
map<int, int> diagonalSum;
diagonalSumUtil(root, 0, diagonalSum);
map<int, int>::iterator it;
cout << "Diagonal sum in a binary tree is - ";
for(it = diagonalSum.begin();
it != diagonalSum.end(); ++it)
{
cout << it->second << " ";
}
}
// Driver code
int main()
{
struct Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(9);
root->left->right = newNode(6);
root->right->left = newNode(4);
root->right->right = newNode(5);
root->right->left->right = newNode(7);
root->right->left->left = newNode(12);
root->left->right->left = newNode(11);
root->left->left->right = newNode(10);
diagonalSum(root);
return 0;
}
// This code is contributed by Aditya Goel