-
Notifications
You must be signed in to change notification settings - Fork 0
/
102-binary_tree_is_complete.c
58 lines (50 loc) · 1.27 KB
/
102-binary_tree_is_complete.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_is_complete - checks if a binary tree is complete
* @tree: a pointer to the root node of the tree to check
*
* Return: 1 if the tree is complete
* 0 if the tree is not complete
* 0 if tree is NULL
*/
int binary_tree_is_complete(const binary_tree_t *tree)
{
size_t size;
if (!tree)
return (0);
size = binary_tree_size(tree);
return (btic_helper(tree, 0, size));
}
/**
* btic_helper - checks if a binary tree is complete
* @tree: a pointer to the root node of the tree to check
* @index: node index to check
* @size: number of nodes in the tree
*
* Return: 1 if the tree is complete
* 0 if the tree is not complete
* 0 if tree is NULL
*/
int btic_helper(const binary_tree_t *tree, size_t index, size_t size)
{
if (!tree)
return (1);
if (index >= size)
return (0);
return (btic_helper(tree->left, 2 * index + 1, size) &&
btic_helper(tree->right, 2 * index + 2, size));
}
/**
* binary_tree_size - measures the size of a binary tree
* @tree: tree to measure the size of
*
* Return: size of the tree
* 0 if tree is NULL
*/
size_t binary_tree_size(const binary_tree_t *tree)
{
if (!tree)
return (0);
return (binary_tree_size(tree->left) +
binary_tree_size(tree->right) + 1);
}