-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBFS.c
91 lines (74 loc) · 1.91 KB
/
BFS.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
#include <stdio.h>
#include <stdlib.h>
#define MAX_Q_SIZE 500
/* A binary tree node has data,
pointer to left child
and a pointer to right child */
struct node {
int data;
struct node* left;
struct node* right;
};
struct node** createQueue(int*, int*);
void enQueue(struct node**, int*, struct node*);
struct node* deQueue(struct node**, int*);
/* Given a binary tree, print its nodes in level order
using array for implementing queue */
void printLevelOrder(struct node* root)
{
int rear, front;
struct node** queue = createQueue(&front, &rear);
struct node* temp_node = root;
while (temp_node) {
printf("%d ", temp_node->data);
/*Enqueue left child */
if (temp_node->left)
enQueue(queue, &rear, temp_node->left);
/*Enqueue right child */
if (temp_node->right)
enQueue(queue, &rear, temp_node->right);
/*Dequeue node and make it temp_node*/
temp_node = deQueue(queue, &front);
}
}
/*UTILITY FUNCTIONS*/
struct node** createQueue(int* front, int* rear)
{
struct node** queue = (struct node**)malloc(
sizeof(struct node*) * MAX_Q_SIZE);
*front = *rear = 0;
return queue;
}
void enQueue(struct node** queue, int* rear,
struct node* new_node)
{
queue[*rear] = new_node;
(*rear)++;
}
struct node* deQueue(struct node** queue, int* front)
{
(*front)++;
return queue[*front - 1];
}
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct node* newNode(int data)
{
struct node* node
= (struct node*)malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return (node);
}
int main()
{
struct node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
printf("Level Order traversal of binary tree is \n");
printLevelOrder(root);
return 0;
}