-
Notifications
You must be signed in to change notification settings - Fork 0
/
101-binary_tree_levelorder.c
executable file
·86 lines (76 loc) · 1.43 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
#include "binary_trees.h"
line_t **node_add(line_t **head, binary_tree_t *tree)
{
line_t *current;
line_t *new = malloc(sizeof(line_t));
new->node = tree;
new->next = NULL;
if (*head == NULL || head == NULL)
*head = new;
else
{
current = *head;
while (current->next != NULL)
current = current->next;
current->next = new;
}
return (head);
}
void node_free(line_t **head)
{
line_t *current;
if (head == NULL || *head == NULL)
return;
while ((*head) != NULL)
{
current = (*head);
(*head) = (*head)->next;
free(current->node);
free(current);
}
head = NULL;
}
int count(line_t **head)
{
int i = 0;
if (head == NULL || *head == NULL)
return (0);
while ((*head) != NULL)
{
i++;
(*head) = (*head)->next;
}
return (i);
}
void binary_tree_levelorder(const binary_tree_t *tree, void (*func)(int))
{
line_t **head = NULL, **head2;
if (tree == NULL || func == NULL)
return;
func(tree->n);
if (tree->left != NULL)
head = node_add(head, tree->left);
if (tree->right != NULL)
head = node_add(head, tree->right);
while (count(head) > 1 && (*head)->next != NULL &&
(*head)->next->node->left != NULL &&
(*head)->next->node->right != NULL)
{
while ((*head) != NULL)
{
func((*head)->node->n);
(*head) = (*head)->next;
}
head2 = NULL;
while ((*head) != NULL)
{
if ((*head)->node->left != NULL)
head2 = node_add(head2, (*head)->node->left);
if ((*head)->node->right != NULL)
head2 = node_add(head2, (*head)->node->right);
(*head) = (*head)->next;
}
free(head);
head = head2;
}
}