Iterative approach to check if a Binary Tree is Perfect

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++
// C++ program to check if the// given binary tree is perfect#include <bits/stdc++.h>using namespace std;Â
// A binary tree nodestruct Node {Â Â Â Â int data;Â Â Â Â Node *left, *right;};Â
// Utility function to allocate memory for a new nodeNode* newNode(int data){Â Â Â Â Node* node = new (Node);Â Â Â Â node->data = data;Â Â Â Â node->left = node->right = NULL;Â Â Â Â return (node);}Â
// Function to check if the given tree is perfectbool CheckPerfectTree(Node* root){Â Â Â Â queue<Node*> q;Â
    // Push the root node    q.push(root);Â
    // Flag to check if leaf nodes have been found    int flag = 0;Â
    while (!q.empty()) {        Node* temp = q.front();        q.pop();Â
        // If current node has both left and right child        if (temp->left && temp->right) {            // If a leaf node has already been found            // then return false            if (flag == 1)                return false;Â
            // If a leaf node has not been discovered yet            // push the left and right child in the queue            else {                q.push(temp->left);                q.push(temp->right);            }        }Â
        // If a leaf node is found mark flag as one        else if (!temp->left && !temp->right) {            flag = 1;        }Â
        // If the current node has only one child        // then return false        else if (!temp->left || !temp->right)            return false;    }Â
    // If the given tree is perfect return true    return true;}Â
// Driver codeint 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
// Java program to check if the // given binary tree is perfect import java.util.*;Â
class GFG{Â Â Â Â Â // A binary tree node static class Node { Â Â Â Â int data; Â Â Â Â Node left, right; }; Â
// Utility function to allocate memory for a new node static Node newNode(int data) { Â Â Â Â Node node = new Node(); Â Â Â Â node.data = data; Â Â Â Â node.left = node.right = null; Â Â Â Â return (node); } Â
// Function to check if the given tree is perfect static boolean CheckPerfectTree(Node root) { Â Â Â Â Queue<Node> q = new LinkedList<Node>(); Â
    // add the root node     q.add(root); Â
    // Flag to check if leaf nodes have been found     int flag = 0; Â
    while (q.size() > 0)    {         Node temp = q.peek();         q.remove(); Â
        // If current node has both left and right child         if (temp.left != null && temp.right != null)         {             // If a leaf node has already been found             // then return false             if (flag == 1)                 return false; Â
            // If a leaf node has not been discovered yet             // add the left and right child in the queue             else            {                 q.add(temp.left);                 q.add(temp.right);             }         } Â
        // If a leaf node is found mark flag as one         else if (temp.left == null && temp.right == null)         {             flag = 1;         } Â
        // If the current node has only one child         // then return false         else if (temp.left == null || temp.right == null)             return false;     } Â
    // If the given tree is perfect return true     return true; } Â
// Driver code 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"); } }Â
// This code is contributed by Arnab Kundu |
Python3
# Python3 program to check if the # given binary tree is perfect import sysimport mathÂ
# A binary tree nodeclass Node:    def __init__(self, data):        self.data = data        self.left = None        self.right = NoneÂ
# Utility function to allocate # memory for a new node def newNode(data):Â Â Â Â return Node(data)Â
# Function to check if the # given tree is perfectdef CheckPerfectTree(root):Â Â Â Â q = []Â
    # Push the root node    q.append(root)Â
    # Flag to check if leaf nodes     # have been found     flag = 0         while(q):        temp = q[0]        q.pop(0)Â
        # If current node has both         # left and right child        if (temp.left and temp.right):                         # If a leaf node has already been found             # then return false             if (flag == 1):                return FalseÂ
            # If a leaf node has not been discovered yet             # push the left and right child in the queue             else:                q.append(temp.left)                q.append(temp.right)Â
        # If a leaf node is found         # mark flag as one            elif(not temp.left and             not temp.right):            flag = 1Â
        # If the current node has only one child         # then return false         elif(not temp.left or             not temp.right):            return False                 # If the given tree is perfect    # return true    return TrueÂ
# Driver Codeif __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")Â
# This code is contributed# by Vikash Kumar 37 |
C#
// C# program to check if the // given binary tree is perfectusing System;using System.Collections.Generic; Â Â Â Â Â class GFG{Â Â Â Â Â // A binary tree node public class Node { Â Â Â Â public int data; Â Â Â Â public Node left, right; }; Â
// Utility function to allocate// memory for a new node static Node newNode(int data) { Â Â Â Â Node node = new Node(); Â Â Â Â node.data = data; Â Â Â Â node.left = node.right = null; Â Â Â Â return (node); } Â
// Function to check if the given tree is perfect static Boolean CheckPerfectTree(Node root) { Â Â Â Â Queue<Node > q = new Queue<Node>(); Â
    // add the root node     q.Enqueue(root); Â
    // Flag to check if leaf nodes    // have been found     int flag = 0; Â
    while (q.Count > 0)    {         Node temp = q.Peek();         q.Dequeue(); Â
        // If current node has both         // left and right child         if (temp.left != null &&             temp.right != null)         {             // If a leaf node has already been found             // then return false             if (flag == 1)                 return false; Â
            // If a leaf node has not been discovered yet             // add the left and right child in the queue             else            {                 q.Enqueue(temp.left);                 q.Enqueue(temp.right);             }         } Â
        // If a leaf node is found mark flag as one         else if (temp.left == null &&                 temp.right == null)         {             flag = 1;         } Â
        // If the current node has only one child         // then return false         else if (temp.left == null ||                 temp.right == null)             return false;     } Â
    // If the given tree is perfect return true     return true; } Â
// Driver code 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"); } }Â
// This code is contributed by Rajput-Ji |
Javascript
<script>// Javascript program to check if the// given binary tree is perfectÂ
// A binary tree nodeclass Node{Â Â Â Â constructor(data)Â Â Â Â {Â Â Â Â Â Â Â Â this.data = data;Â Â Â Â Â Â Â Â this.left = this.right = null;Â Â Â Â }}Â
// Function to check if the given tree is perfectfunction CheckPerfectTree(root){    let q = [];      // add the root node    q.push(root);      // Flag to check if leaf nodes have been found    let flag = 0;      while (q.length > 0)    {        let temp = q[0];        q.shift();          // If current node has both left and right child        if (temp.left != null && temp.right != null)        {            // If a leaf node has already been found            // then return false            if (flag == 1)                return false;              // If a leaf node has not been discovered yet            // add the left and right child in the queue            else            {                q.push(temp.left);                q.push(temp.right);            }        }          // If a leaf node is found mark flag as one        else if (temp.left == null && temp.right == null)        {            flag = 1;        }          // If the current node has only one child        // then return false        else if (temp.left == null || temp.right == null)            return false;    }      // If the given tree is perfect return true    return true;}Â
// Driver codelet 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");Â
// This code is contributed by avanitrachhadiya2155</script> |
Output:Â
No
Â
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 zambiatek!
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



