-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path101-binary_tree_levelorder.c
60 lines (55 loc) · 1.48 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
#include "binary_trees.h"
/**
* binary_tree_height - measures the height of a binary tree
* @tree: pointer to the root node of the tree to measure the height of
*
* Return: the height of the tree. If tree is NULL, return 0
*/
size_t binary_tree_height(const binary_tree_t *tree)
{
size_t left, right;
if (tree == NULL)
return (0);
left = binary_tree_height(tree->left);
right = binary_tree_height(tree->right);
if (left >= right)
return (1 + left);
return (1 + right);
}
/**
* binary_tree_level - perform a function on a specific level of a binary tree
* @tree: pointer to the root of the tree
* @l: level of the tree to perform a function on
* @func: function to perform
*
* Return: void
*/
void binary_tree_level(const binary_tree_t *tree, size_t l, void (*func)(int))
{
if (tree == NULL)
return;
if (l == 1)
func(tree->n);
else if (l > 1)
{
binary_tree_level(tree->left, l - 1, func);
binary_tree_level(tree->right, l - 1, func);
}
}
/**
* binary_tree_levelorder - traverses 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.
* The value in the node must be passed as a parameter to this function
*
* Return: void
*/
void binary_tree_levelorder(const binary_tree_t *tree, void (*func)(int))
{
size_t height, i;
if (tree == NULL || func == NULL)
return;
height = binary_tree_height(tree);
for (i = 1; i <= height; i++)
binary_tree_level(tree, i, func);
}