VOOZH about

URL: https://www.geeksforgeeks.org/dsa/check-weather-given-binary-tree-perfect-not/

⇱ Perfect Binary Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Perfect Binary Tree

Last Updated : 20 May, 2026

A perfect binary tree is a type of binary tree that is completely filled at every level with no missing nodes.

  • All internal nodes have degree 2 and all leaf nodes are at the same level.
  • Number of leaf nodes = 2h where h is height of the binary tree.
  • Number of internal nodes = Leaf nodes - 1 = 2h - 1
  • Total Nodes = Leaf Nodes + Non-leaf nodes + 1 = 2h + 1 - 1
  • Height = log(n + 1) - 1 where n is count of nodes.
  • Can be represented using an array, where the left child of a node at index i is stored at index 2i+1 and the right child is stored at index 2i+2. This makes it easy to access the children of a node and to traverse the tree.

Given a Binary Tree, the task is to check whether the given Binary Tree is a perfect Binary Tree or not.

Examples:

Input: root[] = [7, 4, 9]

👁 blobid0_1778757069

Output: true
Explanation: As the root node 7 has two children and two leaf nodes 4 and 9 are at the same level.

Input: root[] = [7, 3, 8, 2, 5, N, 10, 1, N, N, N, N, N]

👁 blobid3_1778757183

Output: false

[Naive Method] Two Traversals - O(n) Time and O(h) Space

The idea is to first find the depth of the binary tree. Then recursively check whether all leaf nodes are present at the same depth and every internal node has exactly two children. If any node violates these conditions, the tree is not a perfect binary tree.


Output
True

[Expected Approach] Single DFS Traversal - O(n) Time and O(h) Space

The idea is to recursively traverse the tree and store the level of the first leaf node. Then, check whether all other leaf nodes are at the same level and every non-leaf node has exactly two children. If both conditions are satisfied, the tree is a perfect binary tree.


Output
True
Comment
Article Tags: