-
Notifications
You must be signed in to change notification settings - Fork 0
/
101-binary_tree_levelorder_recursive.c
113 lines (101 loc) · 2.45 KB
/
101-binary_tree_levelorder_recursive.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
#include "binary_trees.h"
/**
* struct node_s - singly linked list
* @node: const binary tree node
* @next: points to the next node
*/
typedef struct node_s
{
const binary_tree_t *node;
struct node_s *next;
} ll;
ll *append(ll *head, const binary_tree_t *btnode);
void free_list(ll *head);
ll *get_children(ll *head, const binary_tree_t *parent);
void levels_rec(ll *head, void (*func)(int));
/**
* 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))
{
ll *children = NULL;
func(tree->n);
children = get_children(children, tree);
levels_rec(children, func);
free_list(children);
}
/**
* levels_rec - Calls func on all nodes at each level.
* @head: Pointer to head of linked list with nodes at one level.
* @func: Pointer to a function to call for each node.
*/
void levels_rec(ll *head, void (*func)(int))
{
ll *children = NULL, *curr = NULL;
if (!head)
return;
for (curr = head; curr != NULL; curr = curr->next)
{
func(curr->node->n);
children = get_children(children, curr->node);
}
levels_rec(children, func);
free_list(children);
}
/**
* get_children - appends children of parent to linked list.
* @head: Pointer to head of linked list where children will be appended.
* @parent: Pointer to node whose children we want to append.
* Return: Pointer to head of linked list of children.
*/
ll *get_children(ll *head, const binary_tree_t *parent)
{
if (parent->left)
head = append(head, parent->left);
if (parent->right)
head = append(head, parent->right);
return (head);
}
/**
* append - adds a new node at the end of a linkedlist
* @head: pointer to head of linked list
* @btnode: const binary tree node to append
* Return: pointer to head, or NULL on failure
*/
ll *append(ll *head, const binary_tree_t *btnode)
{
ll *new = NULL, *last = NULL;
new = malloc(sizeof(*new));
if (new)
{
new->node = btnode;
new->next = NULL;
if (!head)
head = new;
else
{
last = head;
while (last->next)
last = last->next;
last->next = new;
}
}
return (head);
}
/**
* free_list - frees all the nodes in a linked list
* @head: pointer to the head of list_t linked list
*/
void free_list(ll *head)
{
ll *ptr = NULL;
while (head)
{
ptr = head->next;
free(head);
head = ptr;
}
}