-
Notifications
You must be signed in to change notification settings - Fork 0
/
16-binary_tree_is_perfect.c
77 lines (71 loc) · 2.17 KB
/
16-binary_tree_is_perfect.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
#include "binary_trees.h"
unsigned char is_leaf(const binary_tree_t *node);
size_t depth(const binary_tree_t *tree);
const binary_tree_t *get_leaf(const binary_tree_t *tree);
int is_perfect_recursive(const binary_tree_t *tree,
size_t leaf_depth, size_t level);
int binary_tree_is_perfect(const binary_tree_t *tree);
/**
* is_leaf - Checks if a node is a leaf of a binary tree.
* @node: A pointer to the node to check.
*
* Return: If the node is a leaf, 1, otherwise, 0.
*/
unsigned char is_leaf(const binary_tree_t *node)
{
return ((node->left == NULL && node->right == NULL) ? 1 : 0);
}
/**
* depth - Returns the depth of a given
* node in a binary tree.
* @tree: A pointer to the node to measure the depth of.
*
* Return: The depth of node.
*/
size_t depth(const binary_tree_t *tree)
{
return (tree->parent != NULL ? 1 + depth(tree->parent) : 0);
}
/**
* get_leaf - Returns a leaf of a binary tree.
* @tree: A pointer to the root node of the tree to find a leaf in.
*
* Return: A pointer to the first encountered leaf.
*/
const binary_tree_t *get_leaf(const binary_tree_t *tree)
{
if (is_leaf(tree) == 1)
return (tree);
return (tree->left ? get_leaf(tree->left) : get_leaf(tree->right));
}
/**
* is_perfect_recursive - Checks if a binary tree is perfect recursively.
* @tree: A pointer to the root node of the tree to check.
* @leaf_depth: The depth of one leaf in the binary tree.
* @level: Level of current node.
*
* Return: If the tree is perfect, 1, otherwise 0.
*/
int is_perfect_recursive(const binary_tree_t *tree,
size_t leaf_depth, size_t level)
{
if (is_leaf(tree))
return (level == leaf_depth ? 1 : 0);
if (tree->left == NULL || tree->right == NULL)
return (0);
return (is_perfect_recursive(tree->left, leaf_depth, level + 1) &&
is_perfect_recursive(tree->right, leaf_depth, level + 1));
}
/**
* binary_tree_is_perfect - Checks if a binary tree is perfect.
* @tree: A pointer to the root node of the tree to check.
*
* Return: If tree is NULL or not perfect, 0.
* Otherwise, 1.
*/
int binary_tree_is_perfect(const binary_tree_t *tree)
{
if (tree == NULL)
return (0);
return (is_perfect_recursive(tree, depth(get_leaf(tree)), 0));
}