Check whether a binary tree is a complete tree or not | Set 2 (Recursive Solution)
A complete binary tree is a binary tree whose all levels except the last level are completely filled and all the leaves in the last level are all to the left side. More information about complete binary trees can be found here.
Below tree is a Complete Binary Tree (All nodes till the second last nodes are filled and all leaves are to the left side)
In the array representation of a binary tree, if the parent node is assigned an index of ‘i’ and left child gets assigned an index of ‘2*i + 1’ while the right child is assigned an index of ‘2*i + 2’. If we represent the above binary tree as an array with the respective indices assigned to the different nodes of the tree above from top to down and left to right.
Hence we proceed in the following manner in order to check if the binary tree is complete binary tree.
Calculate the number of nodes (count) in the binary tree.
Start recursion of the binary tree from the root node of the binary tree with index (i) being set as 0 and the number of nodes in the binary (count).
If the current node under examination is NULL, then the tree is a complete binary tree. Return true.
If index (i) of the current node is greater than or equal to the number of nodes in the binary tree (count) i.e. (i>= count), then the tree is not a complete binary. Return false.
Recursively check the left and right sub-trees of the binary tree for same condition. For the left sub-tree use the index as (2*i + 1) while for the right sub-tree use the index as (2*i + 2).
The time complexity of the above algorithm is O(n). Following is the code for checking if a binary tree is a complete binary tree.