-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path101-binary_tree_levelorder.c
56 lines (48 loc) · 1.33 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
#include "binary_trees.h"
/**
* binary_tree_levelorder - traverst a binary tree using level-order traverse
* @tree: 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))
{
size_t level, maxlevel;
if (!tree || !func)
return;
maxlevel = binary_tree_height(tree) + 1;
for (level = 1; level <= maxlevel; level++)
btlo_helper(tree, func, level);
}
/**
* btlo_helper - goes through a binary tree using post-order traverse
* @tree: tree to traverse
* @func: pointer to a function to call for each node
* @level: the level of the tree to call func upon
*/
void btlo_helper(const binary_tree_t *tree, void (*func)(int), size_t level)
{
if (level == 1)
func(tree->n);
else
{
btlo_helper(tree->left, func, level - 1);
btlo_helper(tree->right, func, level - 1);
}
}
/**
* binary_tree_height - measures the height of a binary tree
* @tree: tree to measure the height of
*
* Return: height of the tree
* 0 if tree is NULL
*/
size_t binary_tree_height(const binary_tree_t *tree)
{
size_t height_l = 0;
size_t height_r = 0;
if (!tree)
return (0);
height_l = tree->left ? 1 + binary_tree_height(tree->left) : 0;
height_r = tree->right ? 1 + binary_tree_height(tree->right) : 0;
return (height_l > height_r ? height_l : height_r);
}