-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path12-binary_tree_leaves.c
More file actions
46 lines (39 loc) · 933 Bytes
/
12-binary_tree_leaves.c
File metadata and controls
46 lines (39 loc) · 933 Bytes
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
#include "binary_trees.h"
/**
* preorder - transverses a Btree in pre-order
* @tree: root of tree/subtree
* @func: function to apply to every node
*
* Description: The pre-order transversal first visits
* the root node and performs its operation, the it
* visits all nodes in the left subtree then all nodes
* in the right subtree
*/
void preorder(const binary_tree_t *tree, size_t *func)
{
if (tree != NULL)
{
/* ACTION ON NODE */
if (tree->left == NULL && tree->right == NULL)
*func += 1;
/* TRANSVERSE */
preorder(tree->left, func);
preorder(tree->right, func);
}
}
/**
* binary_tree_leaves - gets the number of leaves in a Bt
* @tree: root of tree/subtree
*
* NOTE: a leaf is a node that has no child
*
* Return: the total number of leaves
*/
size_t binary_tree_leaves(const binary_tree_t *tree)
{
size_t n_leaf = 0;
if (!tree)
return (0);
preorder(tree, &n_leaf);
return (n_leaf);
}