Find the largest Complete Subtree in a given Binary Tree
Last Updated : 11 Jul, 2025
Given a Binary Tree, the task is to find the size and also the inorder traversal of the largest Complete sub-tree in the given Binary Tree. Complete Binary Tree - A Binary tree is a Complete Binary Tree if all levels are filled except possibly the last level and the last level has all keys as left as possible.
Note: All Perfect Binary Trees are Complete Binary trees but the reverse is not true. If a tree is not complete then it is also not a Perfect Binary Tree.
The idea is to simply traverse the tree in a bottom-up manner. During the recursion, as the process moves from the child nodes back to the parent, the sub-tree information is passed up to the parent node. This information allows the parent node to perform the Complete Tree test in constant time. Both the left and right sub-trees pass details about whether they are Perfect or Complete, along with the maximum size of the largest complete binary sub-tree found so far.
To determine if the parent sub-tree is complete, the following three cases are evaluated:
If the left sub-tree is Perfect and the right sub-tree is Complete, and their heights are equal, then the current sub-tree (rooted at the parent) is a Complete Binary Sub-tree. Its size is equal to the sum of the sizes of the left and right sub-trees plus one (for the root).
If the left sub-tree is Complete and the right sub-tree is Perfect, and the height of the left sub-tree is greater than the height of the right sub-tree by one, then the current sub-tree (rooted at the parent) is a Complete Binary Sub-tree. Its size is again the sum of the sizes of the left and right sub-trees plus one (for the root). However, this sub-tree cannot be Perfect, because in this case, its left child is not perfect.
If neither of the above conditions is satisfied, the current sub-tree cannot be a Complete Binary Tree. In this case, the maximum size of a complete binary sub-tree found so far in either the left or right sub-tree is returned. Additionally, if the current sub-tree is not complete, it cannot be perfect either.
Output
4
10 45 60 70
Time Complexity: O(n), as each node is visited once in the recursion, where n is the total number of nodes in the tree. Auxiliary Space: O(h), due to the size of the stack used for recursion