-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathFind the sum of nodes in binary tree
105 lines (97 loc) · 1.92 KB
/
Find the sum of nodes 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
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#include <stdio.h>
#include <stdlib.h>
struct tree_node
{
struct node *lchild;
struct node *rchild;
int data;
};
struct queue{
int size;
int front ;
int rear;
struct tree_node **Q;
};
void create(struct queue *q,int size)
{
q->size=size;
q->front=q->rear=0;
q->Q=(struct tree_node**)malloc(q->size*sizeof(struct tree_node *));
}
void enqueue(struct queue *q , struct tree_node *x)
{
if((q->rear+1)%q->size == q->front)
printf("Queue is Full\n");
else
{
q->rear=(q->rear+1)%q->size;
q->Q[q->rear]=x;
}
}
struct tree_node * dequeue(struct queue *q )
{
struct tree_node *x = NULL;
if(q->front==q->rear)
printf("Queue is empty\n");
else
{
q->front++;
x = q->Q[q->front];
}
return x;
}
int isEmpty(struct queue q)
{
return q.front==q.rear;
}
//Code For TREEEEE
struct tree_node *root = NULL;
int Tree_create(){
struct tree_node *p,*t;;
int sum=0;
int x;
struct queue q;
create(&q,100);
printf("enter the root value\n");
scanf("%d",&x);
root = (struct tree_node *)malloc(sizeof(struct tree_node *));
root->data = x;
sum=sum+x;
root->lchild = root->rchild=NULL;
enqueue(&q,root);
while(!isEmpty(q))
{
p=dequeue(&q);
printf("Enter left child of %d\t",p->data);
scanf("%d",&x);
if(x!=-1)
{
t = (struct tree_node*)malloc(sizeof(struct tree_node ));
t->data=x;
sum=sum+x;
(t->lchild)=(t->rchild)=NULL;
(p->rchild)=t;
enqueue(&q,t);
}
printf("Enter right child of %d\t",p->data);
scanf("%d",&x);
if(x!=-1)
{
t = (struct tree_node*)malloc(sizeof(struct tree_node ));
t->data=x;
sum=sum+x;
(t->lchild)=(t->rchild)=NULL;
(p->rchild)=t;
enqueue(&q,t);
}
}
return sum;
}
int main(int argc, char** argv) {
int a;
printf("----------------To Find Sum of nodes in tree--------------\n\n");
printf("If you enter -1 in this code node for that particular will not be created futher\n\n\n");
a= Tree_create();
printf("Sum of all the root nodes is %d",a);
return 0;
}