-
Notifications
You must be signed in to change notification settings - Fork 0
/
101-binary_tree_levelorder.c
58 lines (50 loc) · 1.41 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
#include "binary_trees.h"
/**
* 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))
{
size_t level, maxlevel;
if (!tree || !func)
return;
maxlevel = binary_tree_height(tree) + 1;
for (level = 1; level <= maxlevel; level++)
btlo_help(tree, func, level);
}
/**
* btlo_help - Goes through a binary tree using post-order travsersal
*
* @tree: Pointer to the root of the node of the tree to traverse
* @func: Pointer to a function to call for each node
* @level: The tree level
*/
void btlo_help(const binary_tree_t *tree, void (*func)(int), size_t level)
{
if (level == 1)
func(tree->n);
else
{
btlo_help(tree->left, func, level - 1);
btlo_help(tree->right, func, level - 1);
}
}
/**
* binary_tree_height - Measures the height of a binary tree
*
* @tree: Pointer to the root node of the tree to measure the height
* Return: 0 if tree is NULL
*/
size_t binary_tree_height(const binary_tree_t *tree)
{
size_t height_left = 0;
size_t height_right = 0;
if (!tree)
return (0);
height_left = tree->left ? 1 + binary_tree_height(tree->left) : 0;
height_right = tree->right ? 1 + binary_tree_height(tree->right) : 0;
return (height_left > height_right ? height_left : height_right);
}