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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- 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
- Check for Symmetric Binary Tree (Iterative Approach)
- Iterative approach to check if a Binary Tree is Perfect
- 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
- Find the largest Complete Subtree in a given Binary Tree
- Height of a complete binary tree (or Heap) with N nodes
- Largest value in each level of Binary Tree | Set-2 (Iterative Approach)
- Iterative Method to find Height of Binary Tree
- Get level of a node in binary tree | iterative approach
- Iterative method to find ancestors of a given binary tree
- Construct Complete Binary Tree from its Linked List Representation
- Number of edges in mirror image of Complete binary tree