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)
- Check whether a binary tree is a full binary tree or not | Iterative Approach
- Check whether a given binary tree is skewed binary tree or not?
- Check whether a binary tree is a full binary tree or not
- 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 given binary tree is perfect or not
- Iterative Approach to check if two Binary Trees are Isomorphic or not
- 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
- Print All Leaf Nodes of a Binary Tree from left to right | Set-2 ( Iterative Approach )
- Largest value in each level of Binary Tree | Set-2 (Iterative Approach)
- Iterative method to find ancestors of a given binary tree
- Construct Binary Tree from given Parent Array representation | Iterative Approach
- Construct a complete binary tree from given array in level order fashion
- Find the largest Complete Subtree in a given Binary Tree
- Check if a binary tree is subtree of another binary tree | Set 1
- Check if a binary tree is subtree of another binary tree | Set 2