Open In App

Check whether a binary tree is a full binary tree or not | Iterative Approach

Last Updated : 28 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given a binary tree containing n nodes. The problem is to check whether the given binary tree is a full binary tree or not. A full binary tree is defined as a binary tree in which all nodes have either zero or two child nodes. Conversely, there is no node in a full binary tree, which has only one child node. 

Examples: 

Input : 
           1
         /   \
        2     3
       / \  
      4   5
Output : Yes

Input :
           1
         /   \
        2     3
       /  
      4   
Output :No

Approach: In the previous post a recursive solution has been discussed. In this post an iterative approach has been followed. Perform iterative level order traversal of the tree using queue. For each node encountered, follow the steps given below:

  1. If (node->left == NULL && node->right == NULL), it is a leaf node. Discard it and start processing the next node from the queue.
  2. If (node->left == NULL || node->right == NULL), then it means that only child of node is present. Return false as the binary tree is not a full binary tree.
  3. Else, push the left and right child’s of the node on to the queue.

If all the node’s from the queue gets processed without returning false, then return true as the binary tree is a full binary tree.

C++




// C++ implementation to check whether a binary
// tree is a full binary tree or not
#include <bits/stdc++.h>
using namespace std;
 
// structure of a node of binary tree
struct Node {
    int data;
    Node *left, *right;
};
 
// function to get a new node
Node* getNode(int data)
{
    // allocate space
    Node* newNode = (Node*)malloc(sizeof(Node));
 
    // put in the data
    newNode->data = data;
    newNode->left = newNode->right = NULL;
    return newNode;
}
 
// function to check whether a binary tree
// is a full binary tree or not
bool isFullBinaryTree(Node* root)
{
    // if tree is empty
    if (!root)
        return true;
 
    // queue used for level order traversal
    queue<Node*> q;
 
    // push 'root' to 'q'
    q.push(root);
 
    // traverse all the nodes of the binary tree
    // level by level until queue is empty
    while (!q.empty()) {
        // get the pointer to 'node' at front
        // of queue
        Node* node = q.front();
        q.pop();
 
        // if it is a leaf node then continue
        if (node->left == NULL && node->right == NULL)
            continue;
 
        // if either of the child is not null and the
        // other one is null, then binary tree is not
        // a full binary tee
        if (node->left == NULL || node->right == NULL)
            return false;
 
        // push left and right childs of 'node'
        // on to the queue 'q'
        q.push(node->left);
        q.push(node->right);
    }
 
    // binary tree is a full binary tee
    return true;
}
 
// Driver program to test above
int main()
{
    Node* root = getNode(1);
    root->left = getNode(2);
    root->right = getNode(3);
    root->left->left = getNode(4);
    root->left->right = getNode(5);
 
    if (isFullBinaryTree(root))
        cout << "Yes";
    else
        cout << "No";
 
    return 0;
}


Java




// Java implementation to check whether a binary
// tree is a full binary tree or not
import java.util.*;
class GfG {
 
// structure of a node of binary tree
static class Node {
    int data;
    Node left, right;
}
 
// function to get a new node
static Node getNode(int data)
{
    // allocate space
    Node newNode = new Node();
 
    // put in the data
    newNode.data = data;
    newNode.left = null;
    newNode.right = null;
    return newNode;
}
 
// function to check whether a binary tree
// is a full binary tree or not
static boolean isFullBinaryTree(Node root)
{
    // if tree is empty
    if (root == null)
        return true;
 
    // queue used for level order traversal
    Queue<Node> q = new LinkedList<Node> ();
 
    // push 'root' to 'q'
    q.add(root);
 
    // traverse all the nodes of the binary tree
    // level by level until queue is empty
    while (!q.isEmpty()) {
        // get the pointer to 'node' at front
        // of queue
        Node node = q.peek();
        q.remove();
 
        // if it is a leaf node then continue
        if (node.left == null && node.right == null)
            continue;
 
        // if either of the child is not null and the
        // other one is null, then binary tree is not
        // a full binary tee
        if (node.left == null || node.right == null)
            return false;
 
        // push left and right childs of 'node'
        // on to the queue 'q'
        q.add(node.left);
        q.add(node.right);
    }
 
    // binary tree is a full binary tee
    return true;
}
 
// Driver program to test above
public static void main(String[] args)
{
    Node root = getNode(1);
    root.left = getNode(2);
    root.right = getNode(3);
    root.left.left = getNode(4);
    root.left.right = getNode(5);
 
    if (isFullBinaryTree(root))
        System.out.println("Yes");
    else
        System.out.println("No");
}
}


Python3




# Python3 program to find deepest
# left leaf Binary search Tree
 
# Helper function that allocates a 
# new node with the given data and
# None left and right pairs.                                    
class getNode:
 
    # Constructor to create a new node
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
 
# function to check whether a binary 
# tree is a full binary tree or not
def isFullBinaryTree( root) :
 
    # if tree is empty
    if (not root) :
        return True
 
    # queue used for level order
    # traversal
    q = []
 
    # append 'root' to 'q'
    q.append(root)
 
    # traverse all the nodes of the
    # binary tree level by level
    # until queue is empty
    while (not len(q)):
         
        # get the pointer to 'node'
        # at front of queue
        node = q[0]
        q.pop(0)
 
        # if it is a leaf node then continue
        if (node.left == None and
            node.right == None):
            continue
 
        # if either of the child is not None 
        # and the other one is None, then
        # binary tree is not a full binary tee
        if (node.left == None or
            node.right == None):
            return False
 
        # append left and right childs
        # of 'node' on to the queue 'q'
        q.append(node.left)
        q.append(node.right)
     
    # binary tree is a full binary tee
    return True
 
# Driver Code
if __name__ == '__main__':
    root = getNode(1)
    root.left = getNode(2)
    root.right = getNode(3)
    root.left.left = getNode(4)
    root.left.right = getNode(5)
 
    if (isFullBinaryTree(root)) :
        print("Yes" )
    else:
        print("No")
 
# This code is contributed by
# Shubham Singh(SHUBHAMSINGH10)


C#




// C# implementation to check whether a binary
// tree is a full binary tree or not
using System;
using System.Collections.Generic;
 
class GfG
{
 
// structure of a node of binary tree
public class Node
{
    public int data;
    public Node left, right;
}
 
// function to get a new node
static Node getNode(int data)
{
    // allocate space
    Node newNode = new Node();
 
    // put in the data
    newNode.data = data;
    newNode.left = null;
    newNode.right = null;
    return newNode;
}
 
// function to check whether a binary tree
// is a full binary tree or not
static bool isFullBinaryTree(Node root)
{
    // if tree is empty
    if (root == null)
        return true;
 
    // queue used for level order traversal
    Queue<Node> q = new Queue<Node> ();
 
    // push 'root' to 'q'
    q.Enqueue(root);
 
    // traverse all the nodes of the binary tree
    // level by level until queue is empty
    while (q.Count!=0) {
        // get the pointer to 'node' at front
        // of queue
        Node node = q.Peek();
        q.Dequeue();
 
        // if it is a leaf node then continue
        if (node.left == null && node.right == null)
            continue;
 
        // if either of the child is not null and the
        // other one is null, then binary tree is not
        // a full binary tee
        if (node.left == null || node.right == null)
            return false;
 
        // push left and right childs of 'node'
        // on to the queue 'q'
        q.Enqueue(node.left);
        q.Enqueue(node.right);
    }
 
    // binary tree is a full binary tee
    return true;
}
 
// Driver code
public static void Main(String[] args)
{
    Node root = getNode(1);
    root.left = getNode(2);
    root.right = getNode(3);
    root.left.left = getNode(4);
    root.left.right = getNode(5);
 
    if (isFullBinaryTree(root))
        Console.WriteLine("Yes");
    else
        Console.WriteLine("No");
}
}
 
// This code has been contributed by 29AjayKumar


Javascript




<script>
 
    // JavaScript implementation to check whether a binary
    // tree is a full binary tree or not
     
    // A Binary Tree Node
    class Node
    {
        constructor(data) {
           this.left = null;
           this.right = null;
           this.data = data;
        }
    }
 
    // function to get a new node
    function getNode(data)
    {
        // allocate space
        let newNode = new Node(data);
        return newNode;
    }
 
    // function to check whether a binary tree
    // is a full binary tree or not
    function isFullBinaryTree(root)
    {
        // if tree is empty
        if (root == null)
            return true;
 
        // queue used for level order traversal
        let q = [];
 
        // push 'root' to 'q'
        q.push(root);
 
        // traverse all the nodes of the binary tree
        // level by level until queue is empty
        while (q.length > 0) {
            // get the pointer to 'node' at front
            // of queue
            let node = q[0];
            q.shift();
 
            // if it is a leaf node then continue
            if (node.left == null && node.right == null)
                continue;
 
            // if either of the child is not null and the
            // other one is null, then binary tree is not
            // a full binary tee
            if (node.left == null || node.right == null)
                return false;
 
            // push left and right childs of 'node'
            // on to the queue 'q'
            q.push(node.left);
            q.push(node.right);
        }
 
        // binary tree is a full binary tee
        return true;
    }
     
    let root = getNode(1);
    root.left = getNode(2);
    root.right = getNode(3);
    root.left.left = getNode(4);
    root.left.right = getNode(5);
   
    if (isFullBinaryTree(root))
        document.write("Yes");
    else
        document.write("No");
   
</script>


Output

Yes

Time Complexity: O(n). 
Auxiliary Space: O(max), where max is the maximum number of nodes at a particular level. 



Similar Reads

Iterative approach to check if a Binary Tree is BST or not
Given a Binary Tree, the task is to check if the given binary tree is a Binary Search Tree or not. If found to be true, then print "YES". Otherwise, print "NO". Examples: Input: 9 / \ 6 10 / \ \ 4 7 11 / \ \ 3 5 8 Output: YES Explanation: Since the left subtree of each node of the tree consists of smaller valued nodes and the right subtree of each
9 min read
Check whether a binary tree is a full binary tree or not
A full binary tree is defined as a binary tree in which all nodes have either zero or two child nodes. Conversely, there is no node in a full binary tree, which has one child node. More information about full binary trees can be found here. For Example : Recommended PracticeFull binary treeTry It! To check whether a binary tree is a full binary tre
14 min read
Check whether a given Binary Tree is Complete or not | Set 1 (Iterative Solution)
Given a Binary Tree, write a function to check whether the given Binary Tree is Complete Binary Tree or not.A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible. See the following examples. The following trees are examples of Complete Binary Trees 1 /
15+ min read
Iterative Approach to check if two Binary Trees are Isomorphic or not
Given two Binary Trees we have to detect if the two trees are Isomorphic. Two trees are called isomorphic if one of them can be obtained from another by a series of flips, i.e. by swapping left and right children of a number of nodes. Any number of nodes at any level can have their children swapped. Note: Two empty trees are isomorphic. For example
12 min read
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 :
9 min read
Iterative approach to check for children sum property in a Binary Tree
Given a binary tree, write a function that returns true if the tree satisfies below property:For every node, data value must be equal to the sum of data values in left and right children. Consider data value as 0 for NULL children.Examples: Input : 10 / \ 8 2 / \ \ 3 5 2 Output : Yes Input : 5 / \ -2 7 / \ \ 1 6 7 Output : No We have already discus
8 min read
Check for Symmetric Binary Tree (Iterative Approach)
Given a binary tree, check whether it is a mirror of itself without recursion. Examples: Input : 1 / \ 2 2 / \ / \ 3 4 4 3 Output : Symmetric Input : 1 / \ 2 2 \ \ 3 3 Output : Not SymmetricRecommended PracticeSymmetric TreeTry It! We have discussed recursive approach to solve this problem in below post :Symmetric Tree (Mirror Image of itself)In th
10 min read
Deepest left leaf node in a binary tree | iterative approach
Given a Binary Tree, find the deepest leaf node that is left child of its parent. For example, consider the following tree. The deepest left leaf node is the node with value 9. Examples: Input : 1 / \ 2 3 / / \ 4 5 6 \ \ 7 8 / \ 9 10 Output : 9 Recursive approach to this problem is discussed hereFor iterative approach, idea is similar to Method 2 o
8 min read
Deepest right leaf node in a binary tree | Iterative approach
Given a Binary Tree, find the deepest leaf node that is the right child of its parent. For example, consider the following tree. The deepest right leaf node is the node with the value 10. Examples: Input : 1 / \ 2 3 \ / \ 4 5 6 \ \ 7 8 / \ 9 10 Output : 10 The idea is similar to Method 2 of level order traversal Traverse the tree level by level and
7 min read
Largest value in each level of Binary Tree | Set-2 (Iterative Approach)
Given a binary tree containing n nodes. The problem is to find and print the largest value present in each level. Examples: Input : 1 / \ 2 3 Output : 1 3 Input : 4 / \ 9 2 / \ \ 3 5 7 Output : 4 9 7 Approach: In the previous post, a recursive method have been discussed. In this post an iterative method has been discussed. The idea is to perform it
9 min read
Article Tags :
Practice Tags :