Given a Binary Tree, the task is to check whether the given Binary Tree is a perfect Binary Tree or not.
A Binary tree is a Perfect Binary Tree in which all internal nodes have two children and all leaves are at the same level.
Examples:
Input :
1
/ \
2 3
/ \ / \
4 5 6 7
Output : Yes
Input :
20
/ \
8 22
/ \ / \
5 3 4 25
/ \ / \ \
1 10 2 14 6
Output : No
One leaf node with value 4 is not present at the
last level and node with value 25 has
only one child.
We have already discussed the recursive approach. In this post, the iterative approach is discussed.
Approach: The idea is to use a queue and a variable flag, initialized to zero, to check if a leaf node has been discovered. We will check:
- If the current node has two children then we will check for the value of flag. If the value of flag is zero then push the left and right child in the queue, but if the value of flag is one then return false because then that means a leaf node has already been found and in a perfect binary tree all the leaf nodes must be present at the last level, no leaf node should be present at any other level.
- If the current node has no child, that means it is a leaf node, then mark flag as one.
- If the current node has just one child then return false, as in a perfect binary tree all the nodes have two children except for the leaf nodes, which must be present at the last level of the tree.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node *left, *right;
};
Node* newNode( int data)
{
Node* node = new (Node);
node->data = data;
node->left = node->right = NULL;
return (node);
}
bool CheckPerfectTree(Node* root)
{
queue<Node*> q;
q.push(root);
int flag = 0;
while (!q.empty()) {
Node* temp = q.front();
q.pop();
if (temp->left && temp->right) {
if (flag == 1)
return false ;
else {
q.push(temp->left);
q.push(temp->right);
}
}
else if (!temp->left && !temp->right) {
flag = 1;
}
else if (!temp->left || !temp->right)
return false ;
}
return true ;
}
int main()
{
Node* root = newNode(7);
root->left = newNode(5);
root->right = newNode(6);
root->left->left = newNode(8);
root->left->right = newNode(1);
root->right->left = newNode(3);
root->right->right = newNode(9);
root->right->right->right = newNode(13);
root->right->right->left = newNode(10);
if (CheckPerfectTree(root))
printf ( "Yes" );
else
printf ( "No" );
return 0;
}
|
Java
import java.util.*;
class GFG
{
static class Node
{
int data;
Node left, right;
};
static Node newNode( int data)
{
Node node = new Node();
node.data = data;
node.left = node.right = null ;
return (node);
}
static boolean CheckPerfectTree(Node root)
{
Queue<Node> q = new LinkedList<Node>();
q.add(root);
int flag = 0 ;
while (q.size() > 0 )
{
Node temp = q.peek();
q.remove();
if (temp.left != null && temp.right != null )
{
if (flag == 1 )
return false ;
else
{
q.add(temp.left);
q.add(temp.right);
}
}
else if (temp.left == null && temp.right == null )
{
flag = 1 ;
}
else if (temp.left == null || temp.right == null )
return false ;
}
return true ;
}
public static void main(String args[])
{
Node root = newNode( 7 );
root.left = newNode( 5 );
root.right = newNode( 6 );
root.left.left = newNode( 8 );
root.left.right = newNode( 1 );
root.right.left = newNode( 3 );
root.right.right = newNode( 9 );
root.right.right.right = newNode( 13 );
root.right.right.left = newNode( 10 );
if (CheckPerfectTree(root))
System.out.printf( "Yes" );
else
System.out.printf( "No" );
}
}
|
Python3
import sys
import math
class Node:
def __init__( self , data):
self .data = data
self .left = None
self .right = None
def newNode(data):
return Node(data)
def CheckPerfectTree(root):
q = []
q.append(root)
flag = 0
while (q):
temp = q[ 0 ]
q.pop( 0 )
if (temp.left and temp.right):
if (flag = = 1 ):
return False
else :
q.append(temp.left)
q.append(temp.right)
elif ( not temp.left and
not temp.right):
flag = 1
elif ( not temp.left or
not temp.right):
return False
return True
if __name__ = = '__main__' :
root = newNode( 7 )
root.left = newNode( 5 )
root.left.left = newNode( 8 )
root.left.right = newNode( 1 )
root.right = newNode( 6 )
root.right.left = newNode( 3 )
root.right.right = newNode( 9 )
root.right.right.left = newNode( 10 )
root.right.right.right = newNode( 13 )
if CheckPerfectTree(root):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
using System.Collections.Generic;
class GFG
{
public class Node
{
public int data;
public Node left, right;
};
static Node newNode( int data)
{
Node node = new Node();
node.data = data;
node.left = node.right = null ;
return (node);
}
static Boolean CheckPerfectTree(Node root)
{
Queue<Node > q = new Queue<Node>();
q.Enqueue(root);
int flag = 0;
while (q.Count > 0)
{
Node temp = q.Peek();
q.Dequeue();
if (temp.left != null &&
temp.right != null )
{
if (flag == 1)
return false ;
else
{
q.Enqueue(temp.left);
q.Enqueue(temp.right);
}
}
else if (temp.left == null &&
temp.right == null )
{
flag = 1;
}
else if (temp.left == null ||
temp.right == null )
return false ;
}
return true ;
}
public static void Main(String []args)
{
Node root = newNode(7);
root.left = newNode(5);
root.right = newNode(6);
root.left.left = newNode(8);
root.left.right = newNode(1);
root.right.left = newNode(3);
root.right.right = newNode(9);
root.right.right.right = newNode(13);
root.right.right.left = newNode(10);
if (CheckPerfectTree(root))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
Javascript
<script>
class Node
{
constructor(data)
{
this .data = data;
this .left = this .right = null ;
}
}
function CheckPerfectTree(root)
{
let q = [];
q.push(root);
let flag = 0;
while (q.length > 0)
{
let temp = q[0];
q.shift();
if (temp.left != null && temp.right != null )
{
if (flag == 1)
return false ;
else
{
q.push(temp.left);
q.push(temp.right);
}
}
else if (temp.left == null && temp.right == null )
{
flag = 1;
}
else if (temp.left == null || temp.right == null )
return false ;
}
return true ;
}
let root = new Node(7);
root.left = new Node(5);
root.right = new Node(6);
root.left.left = new Node(8);
root.left.right = new Node(1);
root.right.left = new Node(3);
root.right.right = new Node(9);
root.right.right.right = new Node(13);
root.right.right.left = new Node(10);
if (CheckPerfectTree(root))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Time Complexity: O(N), where N is the total number of nodes in the binary tree.
Auxiliary Space: O(N)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
10 Aug, 2021
Like Article
Save Article