forked from LobnaMuhamed/binary_trees
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path101-binary_tree_levelorder.c
executable file
·94 lines (74 loc) · 1.29 KB
/
101-binary_tree_levelorder.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
#include <stdlib.h>
#include "binary_trees.h"
#include <stdio.h>
/**
* binary_tree_levelorder - Goes through a binary tree
* using level-order traversal
* @tree: Pointer to the root node of the tree to traverse
* @func: Pointer to a function to call for each node
*/
void binary_tree_levelorder(const binary_tree_t *tree, void (*func)(int))
{
Q_q *q;
Q_d *tmp;
if (!tree || !func)
return;
q = (Q_q *)malloc(sizeof(Q_q));
if (!q)
return;
q->head = NULL;
q->tail = NULL;
func(tree->n);
push(q, tree->left);
push(q, tree->right);
do {
tmp = pop(q);
if (tmp)
{
func(tmp->data->n);
push(q, tmp->data->left);
push(q, tmp->data->right);
free(tmp);
}
} while (tmp);
if (q)
free(q);
}
/**
* push - Push node
* @q: Struct queue
* @data: The data of the node
*/
void push(Q_q *q, const binary_tree_t *data)
{
Q_d *new_node;
if (q && data)
{
new_node = (Q_d *)malloc(sizeof(Q_d));
if (!new_node)
exit(1);
new_node->data = data;
new_node->next = NULL;
if (!q->head)
q->head = new_node;
if (q->tail)
q->tail->next = new_node;
q->tail = new_node;
}
}
/**
* pop - Pop node
* @q: Struct queue
*
* Return: The node
*/
Q_d *pop(Q_q *q)
{
Q_d *tmp = NULL;
if (q && q->head)
{
tmp = q->head;
q->head = q->head->next;
}
return (tmp);
}