-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmaximum_non_recursive.c
141 lines (138 loc) · 2.67 KB
/
maximum_non_recursive.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *left;
struct node *right;
};
struct queue
{
int size;
int f;
int r;
struct node **arr;
};
struct queue *createQueue()
{
struct queue *q = malloc(sizeof(struct queue));
if (!q)
{
return NULL;
}
q->size = 20;
q->f = -1;
q->r = -1;
q->arr = malloc(q->size * sizeof(struct node *));
if (!q->arr)
{
return NULL;
}
return q;
}
struct node *createNode(int data)
{
struct node *root = malloc(sizeof(struct node));
if (!root)
{
return NULL;
}
root->data = data;
root->left = NULL;
root->right = NULL;
return root;
}
int isEmpty(struct queue *q)
{
return (q->f == -1);
}
int isFull(struct queue *q)
{
return ((q->r + 1) % q->size == q->f);
}
void EnQueue(struct queue *q, struct node *root)
{
if (isFull(q))
{
printf("Queue overflow!!\n");
return;
}
else
{
q->r = (q->r + 1) % q->size;
q->arr[q->r] = root;
if (q->f == -1)
{
q->f = q->r;
}
}
}
struct node *DeQueue(struct queue *q)
{
if (isEmpty(q))
{
printf("Queue underflow!!\n");
return NULL;
}
else
{
struct node *root = q->arr[q->f];
if (q->f == q->r)
{
q->f = -1;
q->r = -1;
}
else
{
q->f = (q->f + 1) % q->size;
}
return root;
}
}
int maxi(struct node *root)
{
if (!root)
{
return 0;
}
int max = 0;
struct queue *q = createQueue();
struct node *temp = NULL;
EnQueue(q, root);
while (!isEmpty(q))
{
temp = DeQueue(q);
if (temp->data > max)
{
max = temp->data;
}
if (temp->left)
{
EnQueue(q, temp->left);
}
if (temp->right)
{
EnQueue(q, temp->right);
}
}
return max;
}
int main()
{
// struct node *root = (struct node *)malloc(sizeof(struct node));
struct node *root = createNode(23); /* 23 */
struct node *r1 = createNode(20); /* /\ */
struct node *r2 = createNode(25); /* 20 25 */
struct node *r3 = createNode(18); /* /\ /\ */
struct node *r4 = createNode(21); /* 18 21 24 26 */
struct node *r5 = createNode(24);
struct node *r6 = createNode(26);
root->left = r1;
root->right = r2;
r1->left = r3;
r1->right = r4;
r2->left = r5;
r2->right = r6;
printf("The greatest element of the tree: %d\n", maxi(root));
return 0;
}