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.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Iterative approach to check if a Binary Tree is Perfect
- Construct XOR tree by Given leaf nodes of Perfect Binary Tree
- Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
- Find sum of all nodes of the given perfect binary tree
- Reverse alternate levels of a perfect binary tree
- Number of edges in a perfect binary tree with N levels
- Find the largest Perfect Subtree in a given Binary Tree
- Check whether a binary tree is a full binary tree or not | Iterative Approach
- Perfect Binary Tree Specific Level Order Traversal | Set 2
- Perfect Binary Tree Specific Level Order Traversal
- Reverse alternate levels of a perfect binary tree using Stack
- Queries to find the maximum Xor value between X and the nodes of a given level of a perfect binary tree
- Print middle level of perfect binary tree without finding height
- Check if a binary tree is subtree of another binary tree | Set 2
- Check whether a binary tree is a full binary tree or not
- Check if a binary tree is subtree of another binary tree | Set 1
- Check whether a given binary tree is skewed binary tree or not?
- Check if max sum level of Binary tree divides tree into two equal sum halves
- Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap
- Check whether a binary tree is a complete tree or not | Set 2 (Recursive Solution)