Given a Binary Tree, write a function to check whether the given Binary Tree is a prefect Binary Tree or not.
A Binary tree is Perfect Binary Tree in which all internal nodes have two children and all leaves are at same level.
The following tree is a perfect binary tree
10 / \ 20 30 / \ / \ 40 50 60 70 18 / \ 15 30
The following tree is not a perfect binary tree
1 / \ 2 3 \ / \ 4 5 6
A Perfect Binary Tree of height h (where height is number of nodes on path from root to leaf) has 2h – 1 nodes.
Below is an idea to check whether a given Binary Tree is perfect or not.
- Find depth of any node (in below tree we find depth of leftmost node). Let this depth be d.
- Now recursively traverse the tree and check for following two conditions.
- Every internal node should have both children non-empty
- All leaves are at depth ‘d’
Time complexity : O(n)
This article is contributed by Nikhil Papisetty. 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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
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 given binary tree is skewed binary tree or not?
- Check whether a binary tree is a full binary tree or not
- Check whether a binary tree is a full binary tree or not | Iterative Approach
- Check whether a binary tree is a complete tree or not | Set 2 (Recursive Solution)
- 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
- Iterative approach to check if a Binary Tree is Perfect
- Check if a Binary Tree is an Even-Odd Tree or not
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
- Find sum of all nodes of the given perfect binary tree
- Find the largest Perfect Subtree in a given Binary Tree
- Queries to find the maximum Xor value between X and the nodes of a given level of a perfect binary tree
- Check whether nodes of Binary Tree form Arithmetic, Geometric or Harmonic Progression
- Check whether every node of binary tree has a value K on itself or its any immediate neighbours
- 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
- Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
- Perfect Binary Tree Specific Level Order Traversal
- Perfect Binary Tree Specific Level Order Traversal | Set 2
- Print middle level of perfect binary tree without finding height