Prepin
Log in

Verify whether the specified binary tree is a complete binary tree.

Approach / Explanation

This question requires you to create a method or function to determine whether a given binary tree is a complete binary tree . A binary tree is a non-linear data structure where each parent node can have a maximum of two children. It is classified as a "complete binary tree" if all levels are fully populated, except possibly the last one, and all nodes are positioned as far left as they can be. To tackle this problem, you need to grasp the fundamentals of binary trees and their traversal methods. Familiarity with an algorithm known as "level order traversal" may also be necessary. Your solution should accurately assess whether the tree is complete.

Suggested Answer

Here’s a way to tackle and implement this problem in Python: def is_complete_binary_tree(root): if root is None: return True queue = [root] flag = False while len(queue) > 0: temp = queue.pop(0) if temp.left: if flag: return False queue.append(temp.left) else: flag = True if temp.right: if flag: return False queue.append(temp.right) else: flag = True return True This function executes a breadth-first search (BFS) level order traversal of the tree. If we find a node that is not fully occupied (meaning it has only one child or no children) during the traversal, and later encounter a node with a child, it indicates that the binary tree is not a complete binary tree.

Alternative Answer

You may also face this issue in Java, and here’s how to address it in that language: public boolean isCompleteBT ( Node root ) { if ( root == null ) return true ; Queue < Node > queue = new LinkedList < > (); queue . add ( root ) ; boolean flag = false ; while ( ! queue . isEmpty ( ) ) { Node temp = queue . remove ( ) ; if ( temp . left != null ) { if ( flag ) return false ; queue . add ( temp . left ) ; } else flag = true ; if ( temp . right != null ) { if ( flag ) return false ; queue . add ( temp . right ) ; } else flag = true ; } return true ; } This function essentially performs the same task as the Python version mentioned earlier, but in Java. It follows the same logic by applying level order traversal to check for any non-full nodes that are succeeded by nodes with children.

Question Details

Difficulty & Category

Medium

Companies

Google

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin LLC · Philadelphia, PA · All rights reserved.