forked from m7robot/binary_trees
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path101-binary_tree_levelorder.c
More file actions
87 lines (72 loc) · 1.47 KB
/
101-binary_tree_levelorder.c
File metadata and controls
87 lines (72 loc) · 1.47 KB
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
#include "binary_trees.h"
/**
* binary_tree_levelorder - a function that goes through a
* binary tree using level-order traversal
* @tree: a pointer to the root node of the tree to traverse
* @func: a pointer to a function to call for each node
*/
void binary_tree_levelorder(const binary_tree_t *tree, void (*func)(int))
{
queue_node_t *front = NULL, *rear = NULL;
const binary_tree_t *current;
if (!tree || !func)
{
return;
}
enqueue(&front, &rear, tree);
while (front)
{
current = front->node;
func(current->n);
if (current->left)
{
enqueue(&front, &rear, current->left);
}
if (current->right)
{
enqueue(&front, &rear, current->right);
}
dequeue(&front);
}
}
/**
* enqueue - Enqueue a node into the queue
* @front: Pointer to the front of the queue
* @rear: Pointer to the rear of the queue
* @node: Pointer to the binary tree node to enqueue
*/
void enqueue(queue_node_t **front, queue_node_t **rear,
const binary_tree_t *node)
{
queue_node_t *new_node = malloc(sizeof(queue_node_t));
if (new_node == NULL)
{
exit(EXIT_FAILURE);
}
new_node->node = node;
new_node->next = NULL;
if (*rear == NULL)
{
*front = new_node;
}
else
{
(*rear)->next = new_node;
}
*rear = new_node;
}
/**
* dequeue - Dequeue a node from the queue
* @front: Pointer to the front of the queue
*/
void dequeue(queue_node_t **front)
{
queue_node_t *temp;
if (*front == NULL)
{
return;
}
temp = *front;
*front = (*front)->next;
free(temp);
}