forked from SedraR78/holbertonschool-binary_trees
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path16-binary_tree_is_perfect.c
More file actions
56 lines (45 loc) · 1.3 KB
/
16-binary_tree_is_perfect.c
File metadata and controls
56 lines (45 loc) · 1.3 KB
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
#include "binary_trees.h"
/**
* binary_tree_is_perfect - Checks if a binary tree is perfect.
* @tree: A pointer to the root node of the tree.
* Return: 1 if the tree is perfect, 0 otherwise.
*/
int binary_tree_is_perfect(const binary_tree_t *tree)
{
size_t height, size;
if (tree == NULL)
return (0);
size = binary_tree_size(tree);
height = binary_tree_height(tree);
return (size == ((size_t)1 << (height + 1)) - 1);
}
/**
* binary_tree_size - Measures the size of a binary tree.
* @tree: A pointer to the root node of the tree.
* Return: The size of the tree, or 0 if tree is NULL.
*/
size_t binary_tree_size(const binary_tree_t *tree)
{
if (tree == NULL)
return (0);
return (1 + binary_tree_size(tree->left) + binary_tree_size(tree->right));
}
/**
* binary_tree_height - Measures the height of a binary tree.
* @tree: A pointer to the root node of the tree.
* Return: The height of the tree, or 0 if tree is NULL.
*/
size_t binary_tree_height(const binary_tree_t *tree)
{
size_t left_height, right_height;
if (tree == NULL)
return (0);
if (tree->left == NULL && tree->right == NULL)
return (0);
left_height = binary_tree_height(tree->left);
right_height = binary_tree_height(tree->right);
if (left_height > right_height)
return (left_height + 1);
else
return (right_height + 1);
}