-
Notifications
You must be signed in to change notification settings - Fork 0
/
101-binary_tree_levelorder.c
128 lines (124 loc) · 2.4 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
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
#include "binary_trees.h"
/**
* binary_tree_height - Function that measures the height of a binary tree
* @tree: tree to go through
* Return: the height
*/
size_t binary_tree_height(const binary_tree_t *tree)
{
size_t l = 0;
size_t r = 0;
if (tree == NULL)
{
return (0);
}
else
{
if (tree)
{
l = tree->left ? 1 + binary_tree_height(tree->left) : 0;
r = tree->right ? 1 + binary_tree_height(tree->right) : 0;
}
return ((l > r) ? l : r);
}
}
/**
* binary_tree_depth - depth of specified node from root
* @tree: node to check the depth
* Return: 0 is it is the root or number of depth
*/
size_t binary_tree_depth(const binary_tree_t *tree)
{
return ((tree && tree->parent) ? 1 + binary_tree_depth(tree->parent) : 0);
}
/**
* linked_node - this function makes a linked list from depth level and node
* @head: pointer to head of linked list
* @tree: node to store
* @level: depth of node to store
* Return: Nothing
*/
void linked_node(link_t **head, const binary_tree_t *tree, size_t level)
{
link_t *new, *aux;
new = malloc(sizeof(link_t));
if (new == NULL)
{
return;
}
new->n = level;
new->node = tree;
if (*head == NULL)
{
new->next = NULL;
*head = new;
}
else
{
aux = *head;
while (aux->next != NULL)
{
aux = aux->next;
}
new->next = NULL;
aux->next = new;
}
}
/**
* recursion - goes through the complete tree and each stores each node
* in linked_node function
* @head: pointer to head of linked list
* @tree: node to check
* Return: Nothing by default it affects the pointer
*/
void recursion(link_t **head, const binary_tree_t *tree)
{
size_t level = 0;
if (tree != NULL)
{
level = binary_tree_depth(tree);
linked_node(head, tree, level);
recursion(head, tree->left);
recursion(head, tree->right);
}
}
/**
* binary_tree_levelorder - print the nodes element in a lever-order
* @tree: root node
* @func: function to use
* Return: Nothing
*/
void binary_tree_levelorder(const binary_tree_t *tree, void (*func)(int))
{
link_t *head, *aux;
size_t height = 0, count = 0;
if (!tree || !func)
{
return;
}
else
{
height = binary_tree_height(tree);
head = NULL;
recursion(&head, tree);
while (count <= height)
{
aux = head;
while (aux != NULL)
{
if (count == aux->n)
{
func(aux->node->n);
}
aux = aux->next;
}
count++;
}
while (head != NULL)
{
aux = head;
head = head->next;
free(aux);
}
}
}