-
Notifications
You must be signed in to change notification settings - Fork 1
/
16-binary_tree_is_perfect.c
78 lines (66 loc) · 1.72 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include "binary_trees.h"
#include <stdio.h>
#include <stdlib.h>
/**
* binary_tree_is_perfect - checks if a binary tree is perfect
* @tree: a pointer to the root node of the tree to check
* Return: 1 if the tree is perfect
* 0 if the tree is not perfect
* 0 if tree is NULL
*/
int binary_tree_is_perfect(const binary_tree_t *tree)
{
size_t height = 0;
size_t nodes = 0, power = 0;
if (!tree)
return (0);
if (!tree->left && !tree->right)
return (1);
height = binary_tree_height(tree);
nodes = binary_tree_size(tree);
power = (size_t)_pow_recursion(2, height + 1);
return (power - 1 == nodes);
}
/**
*_pow_recursion - returns the value of x raised to the power of y
*@x: the value to exponentiate
*@y: the power to raise x to
*Return: x to the power of y, or -1 if y is negative
*/
int _pow_recursion(int x, int y)
{
if (y < 0)
return (-1);
if (y == 0)
return (1);
else
return (x * _pow_recursion(x, y - 1));
}
/**
* 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);
}
/**
* binary_tree_height - measures the height of a binary tree
* @tree: tree to measure the height of
* Return: height of the tree
* 0 if tree is NULL
*/
size_t binary_tree_height(const binary_tree_t *tree)
{
size_t height_l = 0;
size_t height_r = 0;
if (!tree)
return (0);
height_l = tree->left ? 1 + binary_tree_height(tree->left) : 0;
height_r = tree->right ? 1 + binary_tree_height(tree->right) : 0;
return (height_l > height_r ? height_l : height_r);
}