-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathbinarytree
More file actions
57 lines (43 loc) · 1.18 KB
/
binarytree
File metadata and controls
57 lines (43 loc) · 1.18 KB
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
#include <stdio.h>
#include <stdlib.h>
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;
}
void diagonalSumUtil(struct Node* root, int d, int sum[], int *max) {
if (root == NULL)
return;
sum[d] += root->data;
if (d > *max)
*max = d;
diagonalSumUtil(root->left, d + 1, sum, max);
diagonalSumUtil(root->right, d, sum, max);
}
void diagonalSum(struct Node* root) {
int sum[100] = {0};
int max = 0;
diagonalSumUtil(root, 0, sum, &max);
printf("Diagonal sums:\n");
for (int i = 0; i <= max; i++)
printf("Diagonal %d: %d\n", i, sum[i]);
}
int main() {
struct Node* root = newNode(8);
root->left = newNode(3);
root->right = newNode(10);
root->left->left = newNode(1);
root->left->right = newNode(6);
root->left->right->left = newNode(4);
root->left->right->right = newNode(7);
root->right->right = newNode(14);
root->right->right->left = newNode(13);
diagonalSum(root);
return 0;
}