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.
- Check whether a binary tree is a complete tree or not | Set 2 (Recursive Solution)
- Iterative Boundary traversal of Complete Binary tree
- 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
- Linked complete binary tree & its creation
- Height of a complete binary tree (or Heap) with N nodes
- Find the largest Complete Subtree in a given Binary Tree
- Iterative Search for a key 'x' in Binary Tree
- Print path from root to all nodes in a Complete Binary Tree
- Sum of the mirror image nodes of a complete binary tree in an inorder way
- Construct Complete Binary Tree from its Linked List Representation
- Number of edges in mirror image of Complete binary tree
- Iterative diagonal traversal of binary tree