-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtree.c
104 lines (100 loc) · 2.19 KB
/
tree.c
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
/*A complete binary tree is having 0 or 2 child only,also known as strict or proper binary tree*/
#include<stdio.h>
#include<stdlib.h>
struct node
{
struct node *lchild;
int data;
struct node* rchild;
};
struct queue
{
int size;
int front;
int rear;
struct node **a;
};
void create(struct queue *q,int size)
{
q->size=size;
q->front=q->rear=0;
q->a=(struct node **)malloc(sizeof(struct node*)*q->size);
}
void enqueue(struct queue *q,struct node*p)
{
if((q->rear+1)%q->size==q->front)
printf("Queue is full\n");
else
{
q->rear=(q->rear+1)%q->size;
q->a[q->rear]=p;
}
}
struct node* dequeue(struct queue *q)
{struct node *x=NULL;
if(q->rear==q->front)
printf("Queue is empty\n");
else
{
q->front=(q->front+1)%q->size;
x=q->a[q->front];
return x;
}
}
int isEmpty(struct queue q)
{
return (q.rear==q.front);
}
//queue(for storing the adress of the nodes) creation ends, now tree creation begins;
struct node *root=NULL;
void tree_create()
{
struct node *p,*t;
int x;
struct queue q;
create(&q,50);
printf("Enter the root value\n");
scanf("%d",&x);
root=(struct node*)malloc(sizeof(struct node));
root->data=x;
root->lchild=root->rchild=NULL;
enqueue(&q,root);
while(!isEmpty(q))
{
p=dequeue(&q);
printf("Enter the left child data of %d ",p->data);
scanf("%d",&x);
if(x!=-1)
{
t=(struct node*)malloc(sizeof(struct node));
t->data=x;
t->lchild=t->rchild=NULL;
p->lchild=t;
enqueue(&q,t);
}
printf("Enter the right child data of %d ",p->data);
scanf("%d",&x);
if(x!=-1)
{
t=(struct node*)malloc(sizeof(struct node));
t->data=x;
t->lchild=t->rchild=NULL;
p->rchild=t;
enqueue(&q,t);
}
}
}
void preoder(struct node *p)
{
if(p)
{
printf("%d ",p->data);
preoder(p->lchild);
preoder(p->rchild);
}
}
void main()
{
tree_create();
preoder(root);
}