Given a Binary Tree, the task is to check whether the given Binary Tree is a perfect Binary Tree or not.
A Binary tree is a Perfect Binary Tree in which all internal nodes have two children and all leaves are at the same level.
Input : 1 / \ 2 3 / \ / \ 4 5 6 7 Output : Yes Input : 20 / \ 8 22 / \ / \ 5 3 4 25 / \ / \ \ 1 10 2 14 6 Output : No One leaf node with value 4 is not present at the last level and node with value 25 has only one child.
We have already discussed the recursive approach. In this post, the iterative approach is discussed.
Approach: The idea is to use a queue and a variable flag, initialized to zero, to check if a leaf node has been discovered. We will check:
- If the current node has two children then we will check for the value of flag. If the value of flag is zero then push the left and right child in the queue, but if the value of flag is one then return false because then that means a leaf node has already been found and in a perfect binary tree all the leaf nodes must be present at the last level, no leaf node should be present at any other level.
- If the current node has no child, that means it is a leaf node, then mark flag as one.
- If the current node has just one child then return false, as in a perfect binary tree all the nodes have two children except for the leaf nodes, which must be present at the last level of the tree.
Below is the implementation of the above approach:
- Check for Symmetric Binary Tree (Iterative Approach)
- Check whether a binary tree is a full binary tree or not | Iterative Approach
- Iterative approach to check for children sum property in a Binary Tree
- Largest value in each level of Binary Tree | Set-2 (Iterative Approach)
- Get level of a node in binary tree | iterative approach
- Deepest right leaf node in a binary tree | Iterative approach
- Sum of nodes at maximum depth of a Binary Tree | Iterative Approach
- Construct Binary Tree from given Parent Array representation | Iterative Approach
- Print All Leaf Nodes of a Binary Tree from left to right | Set-2 ( Iterative Approach )
- Deepest left leaf node in a binary tree | iterative approach
- 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
- Check if a Binary Tree is BST : Simple and Efficient Approach
- Check whether a given Binary Tree is Complete or not | Set 1 (Iterative Solution)
- Construct XOR tree by Given leaf nodes of Perfect Binary Tree
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.