-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path16-binary_tree_is_perfect.c
More file actions
46 lines (40 loc) · 1009 Bytes
/
16-binary_tree_is_perfect.c
File metadata and controls
46 lines (40 loc) · 1009 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"
/**
* binary_tree_is_perfect - Check if a binary tree is perfect
* @tree: Pointer to the root node of the tree
*
* Return: 1 if perfect, 0 otherwise
*/
int binary_tree_is_perfect(const binary_tree_t *tree)
{
if (!tree)
return (0);
if (binary_tree_height(tree->left) !=
binary_tree_height(tree->right))
return (0);
if (!tree->left && !tree->right)
return (1);
if (binary_tree_is_perfect(tree->left) &&
binary_tree_is_perfect(tree->right))
return (1);
return (0);
}
/**
* binary_tree_height - Measure the height of a binary tree
* @tree: Pointer to the root node of the tree to measure
*
* Return: The height
*/
size_t binary_tree_height(const binary_tree_t *tree)
{
int left_h = 0, right_h = 0;
if (!tree || (!tree->left && !tree->right))
return (0);
if (tree->left)
left_h = 1 + binary_tree_height(tree->left);
if (tree->right)
right_h = 1 + binary_tree_height(tree->right);
if (left_h > right_h)
return (left_h);
return (right_h);
}