Skip to content

Commit 588a21c

Browse files
authored
Added Binary Tree in C
1 parent c2878b2 commit 588a21c

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

Added Binary Tree in C

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
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+
}

0 commit comments

Comments
 (0)