-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path102-binary_tree_is_complete.c
More file actions
109 lines (95 loc) · 1.7 KB
/
102-binary_tree_is_complete.c
File metadata and controls
109 lines (95 loc) · 1.7 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#include "binary_trees.h"
void free_node_t(node_t **head);
/**
*pop_node_t - freeing a list
*@head: pointer to the start of the list
*Return: Pointer to the new head
*/
node_t *pop_node_t(node_t **head)
{
node_t *tmp;
if (!head || !*head)
return (0);
tmp = *head;
*head = (*head)->next;
free(tmp);
return (*head);
}
/**
*add_node_t - adding a node at the end
*@head: pointer to the start of the list
*@p: Pointer with which to form a new node
*Return: Pointer to the head
*/
node_t *add_node_t(node_t **head, binary_tree_t *p)
{
node_t *ptr, *tmp;
ptr = (node_t *) malloc(sizeof(node_t));
if (ptr == NULL)
return (NULL);
ptr->p = p;
ptr->next = NULL;
if (*head == NULL)
*(head) = ptr;
else
{
tmp = *(head);
while (tmp->next != NULL)
{
tmp = tmp->next;
}
tmp->next = ptr;
}
return (*head);
}
/**
*binary_tree_is_complete - This function checks if a binary tree is complete
*
*@tree: Pointer to the root of the tree
*Return: nothing
*/
int binary_tree_is_complete(const binary_tree_t *tree)
{
node_t *head = NULL;
binary_tree_t *p;
if (!tree)
return (0);
head = add_node_t(&head, (binary_tree_t *)tree);
p = (binary_tree_t *)tree;
while (head)
{
if (!p && head->p)
{
free_node_t(&head);
return (0);
}
p = head->p;
if (p)
{
add_node_t(&head, head->p->left);
add_node_t(&head, head->p->right);
}
head = pop_node_t(&head);
}
return (1);
}
/**
*free_node_t - freeing a list
*@head: pointer to the start of the list
*Return: nothing
*/
void free_node_t(node_t **head)
{
node_t *ptr;
node_t *tmp;
if (!head)
return;
ptr = *head;
while (ptr != NULL)
{
tmp = ptr->next;
free(ptr);
ptr = tmp;
}
*head = NULL;
}