-
Notifications
You must be signed in to change notification settings - Fork 0
/
130-binary_tree_is_heap.c
executable file
·85 lines (70 loc) · 1.78 KB
/
130-binary_tree_is_heap.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
#include "binary_trees.h"
/**
* binary_tree_size - measures the size of a binary tree
*
* @tree: tree root
* Return: 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 (binary_tree_size(tree->left) + binary_tree_size(tree->right) + 1);
}
/**
* tree_is_complete - checks if tree is complete
*
* @tree: pointer to the tree root
* @i: node index
* @cnodes: number of nodes
* Return: 1 if tree is complete, 0 otherwise
*/
int tree_is_complete(const binary_tree_t *tree, int i, int cnodes)
{
if (tree == NULL)
return (1);
if (i >= cnodes)
return (0);
return (tree_is_complete(tree->left, (2 * i) + 1, cnodes) &&
tree_is_complete(tree->right, (2 * i) + 2, cnodes));
}
/**
* binary_tree_is_complete - calls to tree_is_complete function
*
* @tree: tree root
* Return: 1 if tree is complete, 0 otherwise
*/
int binary_tree_is_complete(const binary_tree_t *tree)
{
size_t cnodes;
if (tree == NULL)
return (0);
cnodes = binary_tree_size(tree);
return (tree_is_complete(tree, 0, cnodes));
}
/**
* check_parent - checks if parent has a greater value than its childs
*
* @tree: pointer to the node
* Return: 1 if parent has a greater value, 0 otherwise
*/
int check_parent(const binary_tree_t *tree)
{
if (tree == NULL)
return (1);
if (tree->n > tree->parent->n)
return (0);
return (check_parent(tree->left) && check_parent(tree->right));
}
/**
* binary_tree_is_heap - checks if an input tree is a Max Binary Heap
*
* @tree: pointer to the root of the tree
* Return: 1 if tree is a Max Binary Heap, 0 otherwise
*/
int binary_tree_is_heap(const binary_tree_t *tree)
{
if (!binary_tree_is_complete(tree))
return (0);
return (check_parent(tree->left) && check_parent(tree->right));
}