-
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
85 lines (66 loc) · 1.47 KB
/
16-binary_tree_is_perfect.c
File metadata and controls
85 lines (66 loc) · 1.47 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include "binary_trees.h"
/**
* binary_tree_is_leaf - checks if a node is a leaf
* @node: pointer to the node to check
*
* Return: 1 if node is a leaf, otherwise 0
*/
int binary_tree_is_leaf(const binary_tree_t *node)
{
int leaf = 0;
if (node && !(node->left) && !(node->right))
leaf = 1;
return (leaf);
}
/**
* binary_tree_is_parent_full - checks if a node is a parent
* @node: pointer to the node to check
*
* Return: 1 if node is a parent, otherwise 0
*/
int binary_tree_is_parent_full(const binary_tree_t *node)
{
int parent = 0;
if (node && node->left && node->right)
parent = 1;
return (parent);
}
/**
* height - measures the height of a tree
* @tree: tree root
*
* Return: height
*/
int height(const binary_tree_t *tree)
{
int left = 0;
int right = 0;
if (tree == NULL)
return (-1);
left = height(tree->left);
right = height(tree->right);
if (left > right)
return (left + 1);
return (right + 1);
}
/**
* binary_tree_is_perfect - checks if a binary tree is perfect
*
* @tree: tree root
* Return: 1 if tree is perfect, 0 otherwise
*/
int binary_tree_is_perfect(const binary_tree_t *tree)
{
if (tree && height(tree->left) == height(tree->right))
{
if (height(tree->left) == -1)
return (1);
if (binary_tree_is_leaf(tree->left) &&
binary_tree_is_leaf(tree->right))
return (1);
if (binary_tree_is_parent_full(tree))
return (binary_tree_is_perfect(tree->left) &&
binary_tree_is_perfect(tree->right));
}
return (0);
}