-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path102-binary_tree_is_complete.c
91 lines (85 loc) · 2.1 KB
/
102-binary_tree_is_complete.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
79
80
81
82
83
84
85
86
87
88
89
90
91
#include "binary_trees.h"
#include <stdio.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, and 0 otherwise. If node is NULL, return 0
*/
int binary_tree_is_leaf(const binary_tree_t *node)
{
if (node != NULL && node->left == NULL && node->right == NULL)
return (1);
return (0);
}
/**
* binary_tree_height - measures the height of a binary tree
* @tree: pointer to the root node of the tree to measure the height of
*
* Return: the height of the tree. If tree is NULL, return 0
*/
size_t binary_tree_height(const binary_tree_t *tree)
{
size_t left, right;
if (tree == NULL)
return (0);
left = binary_tree_height(tree->left);
right = binary_tree_height(tree->right);
if (left >= right)
return (1 + left);
return (1 + right);
}
/**
* binary_tree_is_perfect - checks if a binary tree is perfect
* @tree: pointer to the root node of the tree to check
*
* Return: 1 if perfect, 0 otherwise. If tree is NULL, return 0
*/
int binary_tree_is_perfect(const binary_tree_t *tree)
{
binary_tree_t *l, *r;
if (tree == NULL)
return (1);
l = tree->left;
r = tree->right;
if (binary_tree_is_leaf(tree))
return (1);
if (l == NULL || r == NULL)
return (0);
if (binary_tree_height(l) == binary_tree_height(r))
{
if (binary_tree_is_perfect(l) && binary_tree_is_perfect(r))
return (1);
}
return (0);
}
/**
* binary_tree_is_complete - checks if a binary tree is complete
* @tree: pointer to the root node of the tree to check
*
* Return: 1 if complete, 0 otherwise. If tree is NULL, return 0
*/
int binary_tree_is_complete(const binary_tree_t *tree)
{
size_t l_height, r_height;
binary_tree_t *l, *r;
if (tree == NULL)
return (0);
if (binary_tree_is_leaf(tree))
return (1);
l = tree->left;
r = tree->right;
l_height = binary_tree_height(l);
r_height = binary_tree_height(r);
if (l_height == r_height)
{
if (binary_tree_is_perfect(l) && binary_tree_is_complete(r))
return (1);
}
else if (l_height == r_height + 1)
{
if (binary_tree_is_complete(l) && binary_tree_is_perfect(r))
return (1);
}
return (0);
}