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 / \ 2 3 1 / \ 2 3 / 4 1 / \ 2 3 / \ / 4 5 6
The following trees are examples of Non-Complete Binary Trees 1 \ 3 1 / \ 2 3 \ / \ 4 5 6 1 / \ 2 3 / \ 4 5
The method 2 of level order traversal post can be easily modified to check whether a tree is Complete or not. To understand the approach, let us first define the term ‘Full Node’. A node is ‘Full Node’ if both left and right children are not empty (or not NULL).
The approach 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.
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.
1 / \ 2 3 \ 4
Thanks to Guddu Sharma for suggesting this simple and efficient approach.
NOT Complete Binary Tree
Time Complexity: O(n) where n is the number of nodes in given Binary Tree
Auxiliary Space: O(n) for queue.
Please write comments if you find any of the above codes/algorithms incorrect, or find other ways to solve the same problem.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Check whether a binary tree is a complete tree or not | Set 2 (Recursive Solution)
- Iterative Boundary Traversal of Complete Binary tree
- Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
- Check whether a binary tree is a full binary tree or not | Iterative Approach
- Iterative approach to check if a Binary Tree is Perfect
- Check for Symmetric Binary Tree (Iterative Approach)
- Iterative approach to check for children sum property in a Binary Tree
- Check if value exists in level-order sorted complete binary tree
- Iterative Search for a key 'x' in Binary Tree
- Sideways traversal of a Complete Binary Tree
- Linked complete binary tree & its creation
- Iterative diagonal traversal of binary tree
- Height of a complete binary tree (or Heap) with N nodes
- Find the largest Complete Subtree in a given Binary Tree
- Largest value in each level of Binary Tree | Set-2 (Iterative Approach)
- Get level of a node in binary tree | iterative approach
- Iterative method to find ancestors of a given binary tree
- Iterative Method to find Height of Binary Tree
- Sum of the mirror image nodes of a complete binary tree in an inorder way
- Number of edges in mirror image of Complete binary tree