forked from 790hanu/Annex-qr-code-simulator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PerfectBinaryTree.java
63 lines (52 loc) · 1.41 KB
/
PerfectBinaryTree.java
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
class PerfectBinaryTree {
static class Node {
int key;
Node left, right;
}
// Calculate the depth
static int depth(Node node) {
int d = 0;
while (node != null) {
d++;
node = node.left;
}
return d;
}
// Check if the tree is perfect binary tree
static boolean is_perfect(Node root, int d, int level) {
// Check if the tree is empty
if (root == null)
return true;
// If for 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
static boolean is_Perfect(Node root) {
int d = depth(root);
return is_perfect(root, d, 0);
}
// Create a new node
static Node newNode(int k) {
Node node = new Node();
node.key = k;
node.right = null;
node.left = null;
return node;
}
public static void main(String args[]) {
Node root = null;
root = newNode(1);
root.left = newNode(2);
root.right = newNode(3);
root.left.left = newNode(4);
root.left.right = newNode(5);
if (is_Perfect(root) == true)
System.out.println("The tree is a perfect binary tree");
else
System.out.println("The tree is not a perfect binary tree");
}
}