-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path13-binary_tree_nodes.c
More file actions
46 lines (39 loc) · 945 Bytes
/
13-binary_tree_nodes.c
File metadata and controls
46 lines (39 loc) · 945 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_nodes - gets the number of nodes in a Bt
* @tree: root of tree/subtree
*
* NOTE: node = total node - leaves
*
* Return: the total number of nodes with at least one child
*/
size_t binary_tree_nodes(const binary_tree_t *tree)
{
size_t n_node = 0;
if (!tree)
return (0);
preorder(tree, &n_node);
return (n_node);
}