forked from NitulKalita/Data-Structures
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPerfect Binary Tree.c
More file actions
68 lines (57 loc) · 1.48 KB
/
Perfect Binary Tree.c
File metadata and controls
68 lines (57 loc) · 1.48 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
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node* left;
struct node* right;
};
// Creating a new node
struct node* newnode(int data) {
struct node* node = (struct node*)malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return (node);
}
// Calculate the depth
int depth(struct node* node) {
int d = 0;
while (node != NULL) {
d++;
node = node->left;
}
return d;
}
// Check if the tree is perfect
bool is_perfect(struct node* root, int d, int level) {
// Check if the tree is empty
if (root == NULL)
return true;
// Check the presence of children
if (root->left == NULL && root->right == NULL)
return (d == level + 1);
if (root->left == NULL || root->right == NULL)
return false;
return is_perfect(root->left, d, level + 1) &&
is_perfect(root->right, d, level + 1);
}
// Wrapper function
bool is_Perfect(struct node* root) {
int d = depth(root);
return is_perfect(root, d, 0);
}
int main() {
struct node* root = NULL;
root = newnode(1);
root->left = newnode(2);
root->right = newnode(3);
root->left->left = newnode(4);
root->left->right = newnode(5);
root->right->left = newnode(6);
root->right->right = newnode(7);
if (is_Perfect(root))
printf("The tree is a perfect binary tree\n");
else
printf("The tree is not a perfect binary tree\n");
}