-
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
53 lines (49 loc) · 1.22 KB
/
Copy path16-binary_tree_is_perfect.c
File metadata and controls
53 lines (49 loc) · 1.22 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
#include "binary_trees.h"
/**
* get_depth - get the depth of the tree.
*
* @tree: pointer to the root of the tree.
*
* Return: tree depth.
*/
size_t get_depth(const binary_tree_t *tree)
{
if (tree == NULL)
return (0);
if (tree->left != NULL)
return (get_depth(tree->left) + 1);
return (0);
}
/**
* binary_tree_is_perfect - function that checks if a binary tree is perfect.
*
* @tree: pointer to the root of the tree to check.
*
* Return: 1 if the tree is perfect, 0 otherwise.
*/
int binary_tree_is_perfect(const binary_tree_t *tree)
{
size_t depth = 0;
if (tree == NULL)
return (0);
depth = get_depth(tree);
return (is_perfect(tree, 0, depth));
}
/**
* is_perfect - recursive function to check if the tree perfect.
*
* @tree: pointer to the tree root.
* @depth: current depth.
* @tree_depth: the depth of the tree.
*
* Return: 1 if the tree is perfect, 0 otherwise.
*/
int is_perfect(const binary_tree_t *tree, size_t depth, size_t tree_depth)
{
if (depth == tree_depth && (tree->left == NULL && tree->right == NULL))
return (1);
if (tree->left != NULL && tree->right != NULL)
return (is_perfect(tree->right, depth + 1, tree_depth) &&
is_perfect(tree->left, depth + 1, tree_depth));
return (0);
}