File tree Expand file tree Collapse file tree 1 file changed +58
-0
lines changed
Expand file tree Collapse file tree 1 file changed +58
-0
lines changed Original file line number Diff line number Diff line change 1+ #include <stdio.h>
2+ #include <stdlib.h>
3+
4+ struct Node {
5+ int data;
6+ struct Node *left, *right;
7+ };
8+
9+ struct Node* newNode(int data) {
10+ struct Node* temp = malloc(sizeof(struct Node));
11+ temp->data = data;
12+ temp->left = temp->right = NULL;
13+ return temp;
14+ }
15+
16+ void diagonalSum(struct Node* root) {
17+ if (!root) return;
18+
19+ int sums[1000] = {0};
20+ int idx = 0;
21+
22+ struct Node* queue[1000];
23+ int front = 0, rear = 0;
24+
25+ queue[rear++] = root;
26+
27+ while (front < rear) {
28+ int size = rear - front;
29+ while (size--) {
30+ struct Node* temp = queue[front++];
31+ while (temp) {
32+ sums[idx] += temp->data;
33+ if (temp->left)
34+ queue[rear++] = temp->left;
35+ temp = temp->right;
36+ }
37+ }
38+ idx++;
39+ }
40+
41+ for (int i = 0; i < idx; i++)
42+ printf("Diagonal %d Sum = %d\n", i, sums[i]);
43+ }
44+
45+ int main() {
46+ struct Node* root = newNode(8);
47+ root->left = newNode(3);
48+ root->right = newNode(10);
49+ root->left->left = newNode(1);
50+ root->left->right = newNode(6);
51+ root->right->right = newNode(14);
52+ root->left->right->left = newNode(4);
53+ root->left->right->right = newNode(7);
54+ root->right->right->left = newNode(13);
55+
56+ diagonalSum(root);
57+ return 0;
58+ }
You can’t perform that action at this time.
0 commit comments