-
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
71 lines (55 loc) · 1.53 KB
/
16-binary_tree_is_perfect.c
File metadata and controls
71 lines (55 loc) · 1.53 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
#include <stdlib.h>
#include <stddef.h>
#include "binary_trees.h"
/**
* binary_tree_depth - measures the depth of a binary tree.
*
* @tree: a pointer to the root node of the tree.
* Return: depth of tree, O if tree is NULL.
*/
size_t binary_tree_depth(const binary_tree_t *tree)
{
size_t depth = 0;
if (tree == NULL)
return (0);
if (tree->parent)
depth = 1 + binary_tree_depth(tree->parent);
return (depth);
}
/**
* is_perfect - checks if a binary tree is perfect based on depth and level.
*
* @tree: a pointer to a tree to check.
* @depth: depth of the tree.
* @level: level of current tree node.
* Return: 1 if tree is perfect, 0 otherwise.
*/
int is_perfect(const binary_tree_t *tree, size_t depth, size_t level)
{
int left_sub;
int right_sub;
/* All leaf nodes must be on the same level */
if (tree->left == NULL && tree->right == NULL)
return (depth == level + 1);
/* if internal node has <2 children */
if (tree->left == NULL || tree->right == NULL)
return (1);
/* Check if left and right subtrees are perfect */
left_sub = is_perfect(tree->left, depth, level + 1);
right_sub = is_perfect(tree->right, depth, level + 1);
return (left_sub && right_sub);
}
/**
* binary_tree_is_perfect - checks if binary tree is perfect.
*
* @tree: a pointer to the tree to check.
* Return: 1 if binary tree is perfect, 0 if otherwise.
*/
int binary_tree_is_perfect(const binary_tree_t *tree)
{
size_t depth = 0;
if (tree == NULL)
return (0);
depth = binary_tree_depth(tree);
return (is_perfect(tree, depth, 0));
}