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 email@example.com. 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.
- Iterative approach to check if a Binary Tree is Perfect
- Find sum of all nodes of the given perfect binary tree
- Find the largest Perfect Subtree in a given Binary Tree
- Reverse alternate levels of a perfect binary tree
- Reverse alternate levels of a perfect binary tree using Stack
- Perfect Binary Tree Specific Level Order Traversal | Set 2
- Perfect Binary Tree Specific Level Order Traversal
- 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 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
- 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
- Given level order traversal of a Binary Tree, check if the Tree is a Min-Heap