Program to check whether a binary tree is complete or not in Python

Suppose we have a binary tree; we have to check whether this is a complete binary tree or not. A complete binary tree is one where all levels are completely filled except possibly the last level, and all nodes in the last level are as far left as possible.

So, if the input is like ?

9 7 10 6 8

then the output will be True

Algorithm

To solve this, we will follow these steps ?

  • Use a queue for level−order traversal

  • Insert root into the queue

  • Use a flag to track when we encounter the first null node

  • While queue is not empty:

    • Remove node from front of queue

    • If node is null, set flag to True

    • If flag is set and we encounter a non−null node, return False

    • Otherwise, add left and right children to queue

  • Return True if traversal completes successfully

Implementation

from collections import deque

class TreeNode:
    def __init__(self, data, left=None, right=None):
        self.data = data
        self.left = left
        self.right = right

class Solution:
    def solve(self, root):
        if not root:
            return True
            
        q = deque()
        q.append(root)
        flag = False
        
        while q:
            temp = q.popleft()
            
            if not temp:
                flag = True
            elif flag and temp:
                return False
            else:
                q.append(temp.left)
                q.append(temp.right)
        
        return True

# Create the tree
ob = Solution()
root = TreeNode(9)
root.left = TreeNode(7)
root.right = TreeNode(10)
root.left.left = TreeNode(6)
root.left.right = TreeNode(8)

print(ob.solve(root))
True

How It Works

The algorithm performs level−order traversal using a queue. When we encounter the first None node (indicating a missing child), we set a flag. If we later find any non−None node after this flag is set, the tree is not complete.

Example with Incomplete Tree

# Example of incomplete binary tree
root2 = TreeNode(1)
root2.left = TreeNode(2)
root2.right = TreeNode(3)
root2.left.left = TreeNode(4)
root2.right.left = TreeNode(5)  # This makes it incomplete

print(ob.solve(root2))
False

Conclusion

This level−order traversal approach efficiently checks if a binary tree is complete by using a flag to detect gaps in the tree structure. The time complexity is O(n) and space complexity is O(w) where w is the maximum width of the tree.

Updated on: 2026-03-25T10:46:52+05:30

519 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements