-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy path101-binary_tree_levelorder.c
More file actions
67 lines (58 loc) · 1.3 KB
/
101-binary_tree_levelorder.c
File metadata and controls
67 lines (58 loc) · 1.3 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
#include "binary_trees.h"
/**
* binary_tree_height_aux - a tree
* @tree: Pointer to
* Return: Trees
*/
size_t binary_tree_height_aux(const binary_tree_t *tree)
{
size_t hleft = 0, hright = 0;
if (!tree)
return (0);
if (tree->left)
hleft = 1 + binary_tree_height_aux(tree->left);
if (tree->right)
hright = 1 + binary_tree_height_aux(tree->right);
if (hleft > hright)
return (hleft);
return (hright);
}
/**
* print_level_order - print each
* @tree: pointer to thse
* @level: level of the tree
* @func: pointer to a node
* Return: void
*/
void print_level_order(const binary_tree_t *tree, int level, void (*func)(int))
{
if (!tree)
return;
if (level == 1)
func(tree->n);
else if (level > 1)
{
print_level_order(tree->left, level - 1, func);
print_level_order(tree->right, level - 1, func);
}
}
/**
* binary_tree_levelorder - function that 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
* Return: void
*/
void binary_tree_levelorder(const binary_tree_t *tree, void (*func)(int))
{
int height = 0;
int len = 1;
if (!tree || !func)
return;
height = binary_tree_height_aux(tree) + 1;
while (len <= height)
{
print_level_order(tree, len, func);
len++;
}
}