-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path16-binary_tree_is_perfect.c
58 lines (50 loc) · 1.29 KB
/
16-binary_tree_is_perfect.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_depth - function that measures the depth of a node
* in a binary tree
* @tree: the binary tree
* Return: the depth of the tree
*/
size_t binary_tree_depth(const binary_tree_t *tree)
{
size_t depth = 0;
while (tree)
{
depth++;
tree = tree->left;
}
return (depth);
}
/**
* is_perfect_fun - function that checks if a binary tree is perfect
* @tree: the binary tree
* @depth: the depth of the tree
* @level: the level of the current node
* Return: 1 if the tree is perfect, 0 otherwise
*/
int is_perfect_fun(const binary_tree_t *tree, int depth, int level)
{
if (tree == NULL)
return (1);
/* if we are leaf by the leftmost (the depth) */
if (!tree->left && !tree->right)
return (depth == level + 1);
/* if we have one child that is not perfect tree */
if (!tree->left || !tree->right)
return (0);
return (is_perfect_fun(tree->left, depth, level + 1) &&
is_perfect_fun(tree->right, depth, level + 1));
}
/**
* binary_tree_is_perfect - function that checks if a binary tree is perfect
* @tree: the binary tree
* Return: 1 if the tree is perfect, 0 otherwise
*/
int binary_tree_is_perfect(const binary_tree_t *tree)
{
int depth;
if (tree == NULL)
return (0);
depth = binary_tree_depth(tree);
return (is_perfect_fun(tree, depth, 0));
}