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.
Examples:
Input:
Output: 10 8 4 9 2 10 5 1 6 3 7 Explanation: The given tree as a whole is itself a Complete Binary Tree.
Input:
Output: 4 10 45 60 70 Explanation: The below subtree is the largest subtree that satisfies the conditions of a Complete Binary Tree
Approach:
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.
C++
// C++ program to find the largest Complete// subtree of the given Binary Tree#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=nullptr;right=nullptr;}};// Class to store details about the subtreeclassSubtreeInfo{public:// To store if the subtree is perfectboolisPerfect;// To store if the subtree is completeboolisComplete;// Size of the subtreeintsize;// Root of the largest complete subtreeNode*rootTree;};// Helper function to calculate height// from the size of the subtreeintgetHeight(intsize){// Height is calculated using the// formula for a perfect binary treereturnceil(log2(size+1));}// Function to find the largest complete binary subtreeSubtreeInfofindCompleteBinaryTree(Node*root){// Initialize the current subtree infoSubtreeInfocurrTree;// Base case: If the tree is emptyif(root==nullptr){currTree.isPerfect=true;currTree.isComplete=true;currTree.size=0;currTree.rootTree=nullptr;returncurrTree;}// Recursive calls for left and right childrenSubtreeInfoleftTree=findCompleteBinaryTree(root->left);SubtreeInforightTree=findCompleteBinaryTree(root->right);// CASE - 1// If the left subtree is perfect, the right// is complete, and their heights are equal,// this subtree is completeif(leftTree.isPerfect&&rightTree.isComplete&&getHeight(leftTree.size)==getHeight(rightTree.size)){currTree.isComplete=true;currTree.isPerfect=rightTree.isPerfect;currTree.size=leftTree.size+rightTree.size+1;currTree.rootTree=root;returncurrTree;}// CASE - 2// If the left subtree is complete, the right// is perfect, and the height of the left is// greater by one, this subtree is completeif(leftTree.isComplete&&rightTree.isPerfect&&getHeight(leftTree.size)==getHeight(rightTree.size)+1){currTree.isComplete=true;currTree.isPerfect=false;currTree.size=leftTree.size+rightTree.size+1;currTree.rootTree=root;returncurrTree;}// CASE - 3// Otherwise, this subtree is neither perfect// nor complete. Return the largest subtreecurrTree.isPerfect=false;currTree.isComplete=false;currTree.size=max(leftTree.size,rightTree.size);currTree.rootTree=(leftTree.size>rightTree.size?leftTree.rootTree:rightTree.rootTree);returncurrTree;}voidinorderPrint(Node*root){if(root!=nullptr){inorderPrint(root->left);cout<<root->data<<" ";inorderPrint(root->right);}}intmain(){// Hardcoded given Binary Tree// 50// / \ // 30 60// / \ / \ // 5 20 45 70// /// 10Node*root=newNode(50);root->left=newNode(30);root->right=newNode(60);root->left->left=newNode(5);root->left->right=newNode(20);root->right->left=newNode(45);root->right->right=newNode(70);root->right->left->left=newNode(10);SubtreeInfoans=findCompleteBinaryTree(root);cout<<ans.size<<endl;inorderPrint(ans.rootTree);return0;}
Java
// Java program to find the largest Complete// subtree of the given Binary Treeimportjava.util.*;classNode{intdata;Nodeleft;Noderight;Node(intx){data=x;left=null;right=null;}}classSubtreeInfo{// To store if the subtree is perfectbooleanisPerfect;// To store if the subtree is completebooleanisComplete;// Size of the subtreeintsize;// Root of the largest complete subtreeNoderootTree;}classGfG{// Helper function to calculate height// from the size of the subtreestaticintgetHeight(intsize){// Height is calculated using the// formula for a perfect binary treereturn(int)Math.ceil(Math.log(size+1)/Math.log(2));}// Function to find the largest complete binary subtreestaticSubtreeInfofindCompleteBinaryTree(Noderoot){// Initialize the current subtree infoSubtreeInfocurrTree=newSubtreeInfo();// Base case: If the tree is emptyif(root==null){currTree.isPerfect=true;currTree.isComplete=true;currTree.size=0;currTree.rootTree=null;returncurrTree;}// Recursive calls for left and right childrenSubtreeInfoleftTree=findCompleteBinaryTree(root.left);SubtreeInforightTree=findCompleteBinaryTree(root.right);// CASE - 1// If the left subtree is perfect, the right// is complete, and their heights are equal,// this subtree is completeif(leftTree.isPerfect&&rightTree.isComplete&&getHeight(leftTree.size)==getHeight(rightTree.size)){currTree.isComplete=true;currTree.isPerfect=rightTree.isPerfect;currTree.size=leftTree.size+rightTree.size+1;currTree.rootTree=root;returncurrTree;}// CASE - 2// If the left subtree is complete, the right// is perfect, and the height of the left is// greater by one, this subtree is completeif(leftTree.isComplete&&rightTree.isPerfect&&getHeight(leftTree.size)==getHeight(rightTree.size)+1){currTree.isComplete=true;currTree.isPerfect=false;currTree.size=leftTree.size+rightTree.size+1;currTree.rootTree=root;returncurrTree;}// CASE - 3// Otherwise, this subtree is neither perfect// nor complete. Return the largest subtreecurrTree.isPerfect=false;currTree.isComplete=false;currTree.size=Math.max(leftTree.size,rightTree.size);currTree.rootTree=(leftTree.size>rightTree.size?leftTree.rootTree:rightTree.rootTree);returncurrTree;}staticvoidinorderPrint(Noderoot){if(root!=null){inorderPrint(root.left);System.out.print(root.data+" ");inorderPrint(root.right);}}publicstaticvoidmain(String[]args){// Hardcoded given Binary Tree// 50// / \// 30 60// / \ / \ // 5 20 45 70// /// 10Noderoot=newNode(50);root.left=newNode(30);root.right=newNode(60);root.left.left=newNode(5);root.left.right=newNode(20);root.right.left=newNode(45);root.right.right=newNode(70);root.right.left.left=newNode(10);SubtreeInfoans=findCompleteBinaryTree(root);System.out.println(ans.size);inorderPrint(ans.rootTree);}}
Python
# Python program to find the largest Complete# subtree of the given Binary TreeimportmathclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=NoneclassSubtreeInfo:# Initialize the subtree infodef__init__(self):self.isPerfect=Falseself.isComplete=Falseself.size=0self.rootTree=None# Helper function to calculate height# from the size of the subtreedefgetHeight(size):# Height is calculated using the# formula for a perfect binary treereturnmath.ceil(math.log2(size+1))# Function to find the largest complete binary subtreedeffindCompleteBinaryTree(root):# Initialize the current subtree infocurrTree=SubtreeInfo()# Base case: If the tree is emptyifrootisNone:currTree.isPerfect=TruecurrTree.isComplete=TruecurrTree.size=0currTree.rootTree=NonereturncurrTree# Recursive calls for left and right childrenleftTree=findCompleteBinaryTree(root.left)rightTree=findCompleteBinaryTree(root.right)# CASE - 1# If the left subtree is perfect, the right# is complete, and their heights are equal,# this subtree is completeif(leftTree.isPerfectandrightTree.isCompleteandgetHeight(leftTree.size)==getHeight(rightTree.size)):currTree.isComplete=TruecurrTree.isPerfect=rightTree.isPerfectcurrTree.size=leftTree.size+rightTree.size+1currTree.rootTree=rootreturncurrTree# CASE - 2# If the left subtree is complete, the right# is perfect, and the height of the left is# greater by one, this subtree is completeif(leftTree.isCompleteandrightTree.isPerfectandgetHeight(leftTree.size)==getHeight(rightTree.size)+1):currTree.isComplete=TruecurrTree.isPerfect=FalsecurrTree.size=leftTree.size+rightTree.size+1currTree.rootTree=rootreturncurrTree# CASE - 3# Otherwise, this subtree is neither perfect# nor complete. Return the largest subtreecurrTree.isPerfect=FalsecurrTree.isComplete=FalsecurrTree.size=max(leftTree.size,rightTree.size)currTree.rootTree=(leftTree.rootTreeifleftTree.size>rightTree.sizeelserightTree.rootTree)returncurrTreedefinorderPrint(root):ifrootisnotNone:inorderPrint(root.left)print(root.data,end=" ")inorderPrint(root.right)if__name__=="__main__":# Hardcoded given Binary Tree# 50# / \# 30 60# / \ / \# 5 20 45 70# /# 10root=Node(50)root.left=Node(30)root.right=Node(60)root.left.left=Node(5)root.left.right=Node(20)root.right.left=Node(45)root.right.right=Node(70)root.right.left.left=Node(10)ans=findCompleteBinaryTree(root)print(ans.size)inorderPrint(ans.rootTree)
C#
// C# program to find the largest Complete// subtree of the given Binary TreeusingSystem;classNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intx){data=x;left=null;right=null;}}// Class to store details about the subtreeclassSubtreeInfo{// To store if the subtree is perfectpublicboolisPerfect;// To store if the subtree is completepublicboolisComplete;// Size of the subtreepublicintsize;// Root of the largest complete subtreepublicNoderootTree;}classGfG{staticintGetHeight(intsize){// Height is calculated using the formula for a// perfect binary treereturn(int)Math.Ceiling(Math.Log(size+1)/Math.Log(2));}// Function to find the largest complete binary subtreestaticSubtreeInfoFindCompleteBinaryTree(Noderoot){// Initialize the current subtree infoSubtreeInfocurrTree=newSubtreeInfo();// Base case: If the tree is emptyif(root==null){currTree.isPerfect=true;currTree.isComplete=true;currTree.size=0;currTree.rootTree=null;returncurrTree;}// Recursive calls for left and right childrenSubtreeInfoleftTree=FindCompleteBinaryTree(root.left);SubtreeInforightTree=FindCompleteBinaryTree(root.right);// CASE - 1// If the left subtree is perfect, the right// is complete, and their heights are equal,// this subtree is completeif(leftTree.isPerfect&&rightTree.isComplete&&GetHeight(leftTree.size)==GetHeight(rightTree.size)){currTree.isComplete=true;currTree.isPerfect=rightTree.isPerfect;currTree.size=leftTree.size+rightTree.size+1;currTree.rootTree=root;returncurrTree;}// CASE - 2// If the left subtree is complete, the right// is perfect, and the height of the left is// greater by one, this subtree is completeif(leftTree.isComplete&&rightTree.isPerfect&&GetHeight(leftTree.size)==GetHeight(rightTree.size)+1){currTree.isComplete=true;currTree.isPerfect=false;currTree.size=leftTree.size+rightTree.size+1;currTree.rootTree=root;returncurrTree;}// CASE - 3// Otherwise, this subtree is neither perfect// nor complete. Return the largest subtreecurrTree.isPerfect=false;currTree.isComplete=false;currTree.size=Math.Max(leftTree.size,rightTree.size);currTree.rootTree=(leftTree.size>rightTree.size?leftTree.rootTree:rightTree.rootTree);returncurrTree;}staticvoidInorderPrint(Noderoot){if(root!=null){InorderPrint(root.left);Console.Write(root.data+" ");InorderPrint(root.right);}}staticvoidMain(string[]args){// Hardcoded given Binary Tree// 50// / \// 30 60// / \ / \ // 5 20 45 70// /// 10Noderoot=newNode(50);root.left=newNode(30);root.right=newNode(60);root.left.left=newNode(5);root.left.right=newNode(20);root.right.left=newNode(45);root.right.right=newNode(70);root.right.left.left=newNode(10);SubtreeInfoans=FindCompleteBinaryTree(root);Console.WriteLine(ans.size);InorderPrint(ans.rootTree);}}
JavaScript
// JavaScript program to find the largest Complete// subtree of the given Binary TreeclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}classSubtreeInfo{constructor(){// To store if the subtree is perfectthis.isPerfect=false;// To store if the subtree is completethis.isComplete=false;// Size of the subtreethis.size=0;// Root of the largest complete subtreethis.rootTree=null;}}// Helper function to calculate height// from the size of the subtreefunctiongetHeight(size){// Height is calculated using the// formula for a perfect binary treereturnMath.ceil(Math.log2(size+1));}// Function to find the largest complete binary subtreefunctionfindCompleteBinaryTree(root){// Initialize the current subtree infoletcurrTree=newSubtreeInfo();// Base case: If the tree is emptyif(root===null){currTree.isPerfect=true;currTree.isComplete=true;currTree.size=0;currTree.rootTree=null;returncurrTree;}// Recursive calls for left and right childrenletleftTree=findCompleteBinaryTree(root.left);letrightTree=findCompleteBinaryTree(root.right);// CASE - 1// If the left subtree is perfect, the right// is complete, and their heights are equal,// this subtree is completeif(leftTree.isPerfect&&rightTree.isComplete&&getHeight(leftTree.size)===getHeight(rightTree.size)){currTree.isComplete=true;currTree.isPerfect=rightTree.isPerfect;currTree.size=leftTree.size+rightTree.size+1;currTree.rootTree=root;returncurrTree;}// CASE - 2// If the left subtree is complete, the right// is perfect, and the height of the left is// greater by one, this subtree is completeif(leftTree.isComplete&&rightTree.isPerfect&&getHeight(leftTree.size)===getHeight(rightTree.size)+1){currTree.isComplete=true;currTree.isPerfect=false;currTree.size=leftTree.size+rightTree.size+1;currTree.rootTree=root;returncurrTree;}// CASE - 3// Otherwise, this subtree is neither perfect// nor complete. Return the largest subtreecurrTree.isPerfect=false;currTree.isComplete=false;currTree.size=Math.max(leftTree.size,rightTree.size);currTree.rootTree=leftTree.size>rightTree.size?leftTree.rootTree:rightTree.rootTree;returncurrTree;}functioninorderPrint(root){letresult=[];functioninorder(node){if(node!==null){inorder(node.left);result.push(node.data);inorder(node.right);}}inorder(root);console.log(result.join(" "));}// Hardcoded given Binary Tree// 50// / \// 30 60// / \ / \ // 5 20 45 70// /// 10letroot=newNode(50);root.left=newNode(30);root.right=newNode(60);root.left.left=newNode(5);root.left.right=newNode(20);root.right.left=newNode(45);root.right.right=newNode(70);root.right.left.left=newNode(10);letans=findCompleteBinaryTree(root);console.log(ans.size);inorderPrint(ans.rootTree);
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