Check whether a given Binary Tree is Complete or not (Iterative Solution)
Last Updated :
23 Jul, 2025
Given a Binary Tree, the task is to check whether the given Binary Tree is a 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.
Examples:
The following trees are examples of Complete Binary Trees:
The following trees are examples of Non-Complete Binary Trees:
[Expected Approach - 1] Using Level-Order Traversal - O(n) Time and O(n) Space
The idea is to do a level order traversal starting from the root. In the traversal, once a node is found which is Not a Full Node, all the following nodes must be leaf nodes. A node is ‘Full Node’ if both left and right children are not empty (or not NULL).
Also, one more thing needs to be checked to handle the below case: If a node has an empty left child, then the right child must be empty.
Below is the implementation of the above approach:
C++
// C++ implementation to check if a
// Binary Tree is complete
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node* left;
Node* right;
Node(int x) {
data = x;
left = nullptr;
right = nullptr;
}
};
// Function to check if the binary tree is complete
bool isCompleteBinaryTree(Node* root) {
if (root == nullptr)
return true;
queue<Node*> q;
q.push(root);
bool end = false;
while (!q.empty()) {
Node* current = q.front();
q.pop();
// Check left child
if (current->left) {
if (end)
return false;
q.push(current->left);
}
else {
// If left child is missing,
// mark the end
end = true;
}
// Check right child
if (current->right) {
if (end)
return false;
q.push(current->right);
}
else {
// If right child is missing,
// mark the end
end = true;
}
}
return true;
}
int main() {
// Representation of Input tree
// 1
// / \
// 2 3
// / \ /
// 4 5 6
Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);
root->right->left = new Node(6);
if (isCompleteBinaryTree(root))
cout << "True" << endl;
else
cout << "False" << endl;
return 0;
}
Java
// Java implementation to check if a
// Binary Tree is complete
import java.util.LinkedList;
import java.util.Queue;
class Node {
int data;
Node left;
Node right;
Node(int x) {
data = x;
left = null;
right = null;
}
}
class GfG {
// Function to check if the binary
// tree is complete
static boolean isCompleteBinaryTree(Node root) {
if (root == null)
return true;
Queue<Node> q = new LinkedList<>();
q.add(root);
boolean end = false;
while (!q.isEmpty()) {
Node current = q.poll();
// Check left child
if (current.left != null) {
if (end)
return false;
q.add(current.left);
}
else {
// If left child is missing,
// mark the end
end = true;
}
// Check right child
if (current.right != null) {
if (end)
return false;
q.add(current.right);
}
else {
// If right child is missing,
// mark the end
end = true;
}
}
return true;
}
public static void main(String[] args) {
// Representation of Input tree
// 1
// / \
// 2 3
// / \ /
// 4 5 6
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
if (isCompleteBinaryTree(root))
System.out.println("True");
else
System.out.println("False");
}
}
Python
# Python implementation to check if a
# Binary Tree is complete
from collections import deque
class Node:
def __init__(self, x):
self.data = x
self.left = None
self.right = None
# Function to check if the binary
# tree is complete
def is_complete_binary_tree(root):
if root is None:
return True
q = deque([root])
end = False
while q:
current = q.popleft()
# Check left child
if current.left:
if end:
return False
q.append(current.left)
else:
# If left child is missing,
# mark the end
end = True
# Check right child
if current.right:
if end:
return False
q.append(current.right)
else:
# If right child is missing,
# mark the end
end = True
return True
if __name__ == "__main__":
# Representation of Input tree
# 1
# / \
# 2 3
# / \ /
# 4 5 6
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
if is_complete_binary_tree(root):
print("True")
else:
print("False")
C#
// C# implementation to check if a
// Binary Tree is complete
using System;
using System.Collections.Generic;
class Node {
public int data;
public Node left;
public Node right;
public Node(int x) {
data = x;
left = null;
right = null;
}
}
// Function to check if the binary
// tree is complete
class GfG {
static bool isCompleteBinaryTree(Node root) {
if (root == null)
return true;
Queue<Node> q = new Queue<Node>();
q.Enqueue(root);
bool end = false;
while (q.Count > 0) {
Node current = q.Dequeue();
// Check left child
if (current.left != null) {
if (end)
return false;
q.Enqueue(current.left);
}
else {
// If left child is missing,
// mark the end
end = true;
}
// Check right child
if (current.right != null) {
if (end)
return false;
q.Enqueue(current.right);
}
else {
// If right child is missing,
// mark the end
end = true;
}
}
return true;
}
static void Main(string[] args) {
// Representation of Input tree
// 1
// / \
// 2 3
// / \ /
// 4 5 6
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
if (isCompleteBinaryTree(root))
Console.WriteLine("True");
else
Console.WriteLine("False");
}
}
JavaScript
// JavaScript implementation to check if a
// Binary Tree is complete
class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}
}
// Function to check if the binary
// tree is complete
function isCompleteBinaryTree(root) {
if (root === null)
return true;
const q = [];
q.push(root);
let end = false;
while (q.length > 0) {
const current = q.shift();
// Check left child
if (current.left) {
if (end)
return false;
q.push(current.left);
}
else {
// If left child is missing,
// mark the end
end = true;
}
// Check right child
if (current.right) {
if (end)
return false;
q.push(current.right);
}
else {
// If right child is missing,
// mark the end
end = true;
}
}
return true;
}
// Representation of Input tree
// 1
// / \
// 2 3
// / \ /
// 4 5 6
const root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
if (isCompleteBinaryTree(root))
console.log("True");
else
console.log("False");
[Expected Approach - 2] Checking position of NULL - O(n) Time and O(n) Space
A simple idea would be to check whether the NULL Node encountered is the last node of the Binary Tree. If the null node encountered in the binary tree is the last node then it is a complete binary tree and if there exists a valid node even after encountering a null node then the tree is not a complete binary tree.
Below is the implementation of the above approach:
C++
// C++ implementation to check if a binary
// tree is complete by position of null
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node* left;
Node* right;
Node(int x) {
data = x;
left = nullptr;
right = nullptr;
}
};
// Function to check if the binary
// tree is complete
bool isCompleteBinaryTree(Node* root) {
if (root == nullptr) {
return true;
}
queue<Node*> q;
q.push(root);
bool nullEncountered = false;
while (!q.empty()) {
Node* curr = q.front();
q.pop();
if (curr == NULL) {
// If we have seen a NULL node, we
// set the flag to true
nullEncountered= true;
}
else {
// If that NULL node is not the last node then
// return false
if (nullEncountered == true) {
return false;
}
// Push both nodes even if
// there are null
q.push(curr->left);
q.push(curr->right);
}
}
return true;
}
int main() {
// Representation of Input tree
// 1
// / \
// 2 3
// / \ /
// 4 5 6
Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
root->left->left = new Node(4);
root->left->right = new Node(5);
root->right->left = new Node(6);
if (isCompleteBinaryTree(root)) {
cout << "True" << endl;
}
else {
cout << "False" << endl;
}
return 0;
}
Java
// Java implementation to check if a binary
// tree is complete by position of null
import java.util.*;
class Node {
int data;
Node left;
Node right;
Node(int x) {
data = x;
left = null;
right = null;
}
}
class GfG {
// Function to check if the binary tree
// is complete
static boolean isCompleteBinaryTree(Node root) {
if (root == null) {
return true;
}
Queue<Node> q = new LinkedList<>();
q.add(root);
boolean nullEncountered = false;
while (!q.isEmpty()) {
Node curr = q.poll();
if (curr == null) {
// If we have seen a null node,
// we set the flag
nullEncountered = true;
}
else {
// If that null node is not the
// last node, return false
if (nullEncountered) {
return false;
}
// Push both nodes even if
// there are null
q.add(curr.left);
q.add(curr.right);
}
}
return true;
}
public static void main(String[] args) {
// Representation of Input tree
// 1
// / \
// 2 3
// / \ /
// 4 5 6
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
if (isCompleteBinaryTree(root)) {
System.out.println("True");
}
else {
System.out.println("False");
}
}
}
Python
# Python implementation to check if a binary
# tree is complete by position of null
class Node:
def __init__(self, x):
self.data = x
self.left = None
self.right = None
# Function to check if the binary
# tree is complete
def isCompleteBinaryTree(root):
if root is None:
return True
queue = []
queue.append(root)
nullEncountered = False
while queue:
curr = queue.pop(0)
if curr is None:
# If we have seen a null node,
# set the flag
nullEncountered = True
else:
# If that null node is not the last
# node, return false
if nullEncountered:
return False
# Push both nodes even if
# there are null
queue.append(curr.left)
queue.append(curr.right)
return True
if __name__ == '__main__':
# Representation of Input tree
# 1
# / \
# 2 3
# / \ /
# 4 5 6
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
if isCompleteBinaryTree(root):
print("True")
else:
print("False")
C#
// C# implementation to check if a binary
// tree is complete by position of null
using System;
using System.Collections.Generic;
class Node {
public int data;
public Node left;
public Node right;
public Node(int x) {
data = x;
left = null;
right = null;
}
}
class GfG {
// Function to check if the binary tree
// is complete
static bool isCompleteBinaryTree(Node root) {
if (root == null) {
return true;
}
Queue<Node> q = new Queue<Node>();
q.Enqueue(root);
bool nullEncountered = false;
while (q.Count > 0) {
Node curr = q.Dequeue();
if (curr == null) {
// If we have seen a null node,
// set the flag
nullEncountered = true;
} else {
// If that null node is not the
// last node, return false
if (nullEncountered) {
return false;
}
// Push both nodes even if there
// are null
q.Enqueue(curr.left);
q.Enqueue(curr.right);
}
}
return true;
}
static void Main() {
// Representation of Input tree
// 1
// / \
// 2 3
// / \ /
// 4 5 6
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
if (isCompleteBinaryTree(root)) {
Console.WriteLine("True");
}
else {
Console.WriteLine("False");
}
}
}
JavaScript
// JavaScript implementation to check if a binary
// tree is complete by position of null
class Node {
constructor(x) {
this.data = x;
this.left = null;
this.right = null;
}
}
// Function to check if the binary
// tree is complete
function isCompleteBinaryTree(root) {
if (root === null) {
return true;
}
const queue = [];
queue.push(root);
let nullEncountered = false;
while (queue.length > 0) {
const curr = queue.shift();
if (curr === null) {
// If we have seen a null node,
// set the flag
nullEncountered = true;
}
else {
// If that null node is not the last
// node, return false
if (nullEncountered) {
return false;
}
// Push both nodes even if
// there are null
queue.push(curr.left);
queue.push(curr.right);
}
}
return true;
}
// Representation of Input tree
// 1
// / \
// 2 3
// / \ /
// 4 5 6
const root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.left = new Node(6);
if (isCompleteBinaryTree(root)) {
console.log("True");
}
else {
console.log("False");
}
Check whether a given Binary Tree is Complete or not | Set 1 (Iterative Solution)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem