Minimum nodes to be removed to make a Binary tree complete
Last Updated : 23 Jul, 2025
Given a binary tree with positive values of nodes, find the minimum number of nodes that need to be removed to transform it into a complete binary tree. Return 0 if the given tree is already complete.
Note: A complete binary tree is a special type of binary tree where all the levels of the tree are filled completely except possibly the lowest level nodes which are filled from as left as possible.
Examples:
Input:
Input example tree 1
Output: 1 Explanation: If we remove node 6, it will transform into the complete binary tree. Note that we could also remove all the nodes of the last level which will also convert it to complete but it will not be the minimum.
Input:
Input example tree 2
Output: 3 Explanation: Nodes 6, 7, and 8 are to be removed.
Using BFS (Breadth First Search): BFS is the most intuitive algorithm here. We will traverse through each level of the given binary tree and when we find the first null node after that all other nodes have to be removed (if present) to convert it to a complete binary tree, So we will count those nodes and return it as our answer.
Steps that were to follow the above approach:
Start the BFS traversal with the root node.
To keep track of the null node create a boolean "nullFound" with starting value of false.
Now when the first null node is found make "nullFound" true.
As soon as "nullFound" becomes true, count all preceding nodes of the same level as well as of below levels.
Below is the code to implement the above steps:
C++
// C++ code for the above approach#include<bits/stdc++.h>usingnamespacestd;// Definition for a binary tree nodestructTreeNode{intval;TreeNode*left;TreeNode*right;TreeNode(intx):val(x),left(NULL),right(NULL){}};intminNodesToBeRemoved_bfs(TreeNode*root){if(!root)return0;// Initialize empty queuequeue<TreeNode*>q;// push root and start bfsq.push(root);// Variable to store if null has// been found or notboolnullFound=false;intans=0;while(q.size()){autofront=q.front();q.pop();if(front->left){q.push(front->left);// If node is present and null// has been found increase the// answer by 1if(nullFound)ans++;}// If node is null make// nullFound trueelsenullFound=true;// Do the same for right nodeif(front->right){q.push(front->right);if(nullFound)ans++;}elsenullFound=true;}// Return the answerreturnans;}// Driver's codeintmain(){/* * * 1 * / \ * 2 3 * / \ \ * 4 5 6 * / \ * 7 8 * * Output: 3 */TreeNode*root=newTreeNode(1);root->left=newTreeNode(2);root->right=newTreeNode(3);root->left->left=newTreeNode(4);root->left->right=newTreeNode(5);root->right->right=newTreeNode(6);root->left->right->left=newTreeNode(7);root->left->right->right=newTreeNode(8);cout<<"Minimum number of nodes to be removed to make ""the tree complete is: ";// Function Callcout<<minNodesToBeRemoved_bfs(root)<<endl;return0;}
Python3
# Python code for the above approachfromqueueimportQueue# Definition for a binary tree nodeclassTreeNode:def__init__(self,x):self.val=xself.left=Noneself.right=NonedefminNodesToBeRemoved_bfs(root:TreeNode)->int:ifnotroot:return0# Initialize empty queueq=Queue()# push root and start bfsq.put(root)# Variable to store if null has# been found or notnullFound=Falseans=0whilenotq.empty():front=q.get()iffront.left:q.put(front.left)# If node is present and null# has been found increase the# answer by 1ifnullFound:ans+=1# If node is null make# nullFound trueelse:nullFound=True# Do the same for right nodeiffront.right:q.put(front.right)ifnullFound:ans+=1else:nullFound=True# Return the answerreturnans# Driver's codeif__name__=='__main__':""" * * 1 * / \ * 2 3 * / \ \ * 4 5 6 * / \ * 7 8 * * Output: 3 """root=TreeNode(1)root.left=TreeNode(2)root.right=TreeNode(3)root.left.left=TreeNode(4)root.left.right=TreeNode(5)root.right.right=TreeNode(6)root.left.right.left=TreeNode(7)root.left.right.right=TreeNode(8)print("Minimum number of nodes to be removed to make ""the tree complete is: ",minNodesToBeRemoved_bfs(root))
C#
// C# code for the above approachusingSystem;usingSystem.Collections.Generic;// Definition for a binary tree nodepublicclassTreeNode{publicintval;publicTreeNodeleft;publicTreeNoderight;publicTreeNode(intx){val=x;left=null;right=null;}}publicclassSolution{publicstaticintminNodesToBeRemoved_bfs(TreeNoderoot){if(root==null)return0;// Initialize empty queueQueue<TreeNode>q=newQueue<TreeNode>();// push root and start bfsq.Enqueue(root);// Variable to store if null has// been found or notboolnullFound=false;intans=0;while(q.Count>0){varfront=q.Dequeue();if(front.left!=null){q.Enqueue(front.left);// If node is present and null// has been found increase the// answer by 1if(nullFound)ans++;}// If node is null make// nullFound trueelsenullFound=true;// Do the same for right nodeif(front.right!=null){q.Enqueue(front.right);if(nullFound)ans++;}elsenullFound=true;}// Return the answerreturnans;}// Driver's codestaticvoidMain(){/* * * 1 * / \ * 2 3 * / \ \ * 4 5 6 * / \ * 7 8 * * Output: 3 */TreeNoderoot=newTreeNode(1);root.left=newTreeNode(2);root.right=newTreeNode(3);root.left.left=newTreeNode(4);root.left.right=newTreeNode(5);root.right.right=newTreeNode(6);root.left.right.left=newTreeNode(7);root.left.right.right=newTreeNode(8);Console.Write("Minimum number of nodes to be removed to make "+"the tree complete is: ");// Function CallConsole.WriteLine(minNodesToBeRemoved_bfs(root));}}
Java
// Java code to implement the above approachimportjava.util.LinkedList;importjava.util.Queue;// Definition for a binary tree nodeclassTreeNode{intval;TreeNodeleft;TreeNoderight;TreeNode(intx){val=x;left=null;right=null;}}publicclassGFG{publicstaticintminNodesToBeRemoved_bfs(TreeNoderoot){if(root==null)return0;// initialize empty queueQueue<TreeNode>q=newLinkedList<>();// push root and start bfsq.offer(root);// variable to store if null has been found or notbooleannullFound=false;intans=0;while(!q.isEmpty()){TreeNodefront=q.poll();if(front.left!=null){q.offer(front.left);// if node is present and null has been// found increase the answer by 1if(nullFound)ans++;}else// if node is null make nullFound truenullFound=true;// do the same for right nodeif(front.right!=null){q.offer(front.right);if(nullFound)ans++;}elsenullFound=true;}// return the answerreturnans;}// Driver's codepublicstaticvoidmain(String[]args){/* * * 1 * / \ * 2 3 * / \ \ * 4 5 6 * / \ * 7 8 * * Output: 3 */TreeNoderoot=newTreeNode(1);root.left=newTreeNode(2);root.right=newTreeNode(3);root.left.left=newTreeNode(4);root.left.right=newTreeNode(5);root.right.right=newTreeNode(6);root.left.right.left=newTreeNode(7);root.left.right.right=newTreeNode(8);System.out.print("Minimum number of nodes to be removed to make the tree complete is: ");System.out.println(minNodesToBeRemoved_bfs(root));}}
JavaScript
// Javascript code for the above approach// Definition for a binary tree nodeclassTreeNode{constructor(val){this.val=val;this.left=null;this.right=null;}}functionminNodesToBeRemoved_bfs(root){if(!root)return0;// Initialize empty queueconstq=[];// push root and start bfsq.push(root);// Variable to store if null has// been found or notletnullFound=false;letans=0;while(q.length){constfront=q.shift();if(front.left){q.push(front.left);// If node is present and null// has been found increase the// answer by 1if(nullFound)ans++;}// If node is null make// nullFound trueelsenullFound=true;// Do the same for right nodeif(front.right){q.push(front.right);if(nullFound)ans++;}elsenullFound=true;}// Return the answerreturnans;}// Driver's code(()=>{/* * * 1 * / \ * 2 3 * / \ \ * 4 5 6 * / \ * 7 8 * * Output: 3 */constroot=newTreeNode(1);root.left=newTreeNode(2);root.right=newTreeNode(3);root.left.left=newTreeNode(4);root.left.right=newTreeNode(5);root.right.right=newTreeNode(6);root.left.right.left=newTreeNode(7);root.left.right.right=newTreeNode(8);console.log("Minimum number of nodes to be removed to make the tree complete is: ");// Function Callconsole.log(minNodesToBeRemoved_bfs(root));})();
Output
Minimum number of nodes to be removed to make the tree complete is: 3
Time Complexity: O(n), (n is the number of nodes) because we are traversing through all the nodes. Auxiliary Space: O(n), (n is the number of nodes) queue is used to contain all the nodes.
Approach:
Using DFS (Depth First Search): Using DFS for this problem is a little bit tricky. We can not directly check, at which level the first null node is found as in the above approach. So we will create an array and store the elements of the given tree (level-wise) in it, at a specific index such that if the tree was complete all the nodes would be filled in the array before a null appears. After the first null node is found the count of all the preceding nodes is our answer.
The first null node found at index 5 after that nodes 6, 7 and 8 are present. So the answer is 3.
Below is the code to implement the above steps:
C++
// C++ code for the above approach#include<bits/stdc++.h>usingnamespacestd;// Definition for a binary tree nodestructTreeNode{intval;TreeNode*left;TreeNode*right;TreeNode(intx):val(x),left(NULL),right(NULL){}};// Function to calculate the// height of the treeintheight(TreeNode*root){if(!root)return0;return1+max(height(root->left),height(root->right));}// dfs traversal to fill the arrayvoiddfs(TreeNode*root,intindex,vector<int>&arr){if(!root)return;arr[index]=root->val;dfs(root->left,2*index+1,arr);dfs(root->right,2*index+2,arr);}intminNodesToBeRemoved_dfs(TreeNode*root){inth=height(root);// Find the size of the arrayintmaxNodes=(1<<h)-1;// Make an array to store the// nodes level wisevector<int>arr(maxNodes,-1);// dfs calldfs(root,0,arr);boolnullFound=false;intans=0;for(auto&it:arr){// If the array value is -1// means node is nullif(it==-1)nullFound=true;// If node is present after the// first null was found// increase the answerif(nullFound&&it!=-1)ans++;}returnans;}// Drivers codeintmain(){/* * 1 * / \ * 2 3 * / \ \ * 4 5 6 * / \ * 7 8 * * Output: 3 */TreeNode*root=newTreeNode(1);root->left=newTreeNode(2);root->right=newTreeNode(3);root->left->left=newTreeNode(4);root->left->right=newTreeNode(5);root->right->right=newTreeNode(6);root->left->right->left=newTreeNode(7);root->left->right->right=newTreeNode(8);cout<<"Minimum number of nodes to be removed to make ""the tree complete is: ";// Function Callcout<<minNodesToBeRemoved_dfs(root)<<endl;return0;}
Java
// Java code to implement the above approachimportjava.util.Arrays;classGFG{staticclassTreeNode{intval;TreeNodeleft;TreeNoderight;TreeNode(intx){val=x;left=null;right=null;}}// function to calculate the height of the treestaticintheight(TreeNoderoot){if(root==null)return0;return1+Math.max(height(root.left),height(root.right));}// dfs traversal to fill the arraystaticvoiddfs(TreeNoderoot,intindex,int[]arr){if(root==null)return;arr[index]=root.val;dfs(root.left,2*index+1,arr);dfs(root.right,2*index+2,arr);}staticintminNodesToBeRemoved_dfs(TreeNoderoot){inth=height(root);// find the size of the arrayintmaxNodes=(1<<h)-1;// make an array to store the nodes level wiseint[]arr=newint[maxNodes];Arrays.fill(arr,-1);// dfs calldfs(root,0,arr);booleannullFound=false;intans=0;for(inti=0;i<arr.length;i++){intit=arr[i];// if the array value is -1 means node is nullif(it==-1)nullFound=true;// if node is present after the first null was// found increase the answerif(nullFound&&it!=-1)ans++;}returnans;}publicstaticvoidmain(String[]args){/* * 1 * / \ * 2 3 * / \ \ * 4 5 6 * / \ * 7 8 * * Output: 3 */TreeNoderoot=newTreeNode(1);root.left=newTreeNode(2);root.right=newTreeNode(3);root.left.left=newTreeNode(4);root.left.right=newTreeNode(5);root.right.right=newTreeNode(6);root.left.right.left=newTreeNode(7);root.left.right.right=newTreeNode(8);System.out.print("Minimum number of nodes to be removed to make the tree complete is: ");System.out.println(minNodesToBeRemoved_dfs(root));}}
Python3
# Python3 code for the above approach# Definition for a binary tree nodeclassTreeNode:def__init__(self,x):self.val=xself.left=Noneself.right=None# Function to calculate the# height of the treedefheight(root):ifnotroot:return0return1+max(height(root.left),height(root.right))# dfs traversal to fill the arraydefdfs(root,index,arr):ifnotroot:returnarr[index]=root.valdfs(root.left,2*index+1,arr)dfs(root.right,2*index+2,arr)defminNodesToBeRemoved_dfs(root):h=height(root)# Find the size of the arraymaxNodes=(1<<h)-1# Make an array to store the# nodes level wisearr=[-1]*maxNodes# dfs calldfs(root,0,arr)nullFound=Falseans=0foritinarr:# If the array value is -1# means node is nullifit==-1:nullFound=True# If node is present after the# first null was found# increase the answerifnullFoundandit!=-1:ans+=1returnans# Drivers codeif__name__=="__main__":""" 1 / \ 2 3 / \ \ 4 5 6 / \ 7 8 Output: 3 """root=TreeNode(1)root.left=TreeNode(2)root.right=TreeNode(3)root.left.left=TreeNode(4)root.left.right=TreeNode(5)root.right.right=TreeNode(6)root.left.right.left=TreeNode(7)root.left.right.right=TreeNode(8)print("Minimum number of nodes to be removed to make the tree complete is: ")# Function Callprint(minNodesToBeRemoved_dfs(root))
C#
// C# code for the above approachusingSystem;usingSystem.Collections.Generic;// Definition for a binary tree nodepublicclassTreeNode{publicintval;publicTreeNodeleft;publicTreeNoderight;publicTreeNode(intx){val=x;left=null;right=null;}}publicclassSolution{// Function to calculate the height of the treepublicintHeight(TreeNoderoot){if(root==null){return0;}return1+Math.Max(Height(root.left),Height(root.right));}// dfs traversal to fill the arraypublicvoidDfs(TreeNoderoot,intindex,List<int>arr){if(root==null){return;}arr[index]=root.val;Dfs(root.left,2*index+1,arr);Dfs(root.right,2*index+2,arr);}publicintMinNodesToBeRemoved(TreeNoderoot){inth=Height(root);// Find the size of the arrayintmaxNodes=(1<<h)-1;// Make an array to store the nodes level wiseList<int>arr=newList<int>(maxNodes);for(inti=0;i<maxNodes;i++){arr.Add(-1);}// dfs callDfs(root,0,arr);boolnullFound=false;intans=0;foreach(intitinarr){// If the array value is -1 means node is nullif(it==-1){nullFound=true;}// If node is present after the first null was found// increase the answerif(nullFound&&it!=-1){ans++;}}returnans;}// Drivers codestaticvoidMain(){/* * 1 * / \ * 2 3 * / \ \ * 4 5 6 * / \ * 7 8 * * Output: 3 */TreeNoderoot=newTreeNode(1);root.left=newTreeNode(2);root.right=newTreeNode(3);root.left.left=newTreeNode(4);root.left.right=newTreeNode(5);root.right.right=newTreeNode(6);root.left.right.left=newTreeNode(7);root.left.right.right=newTreeNode(8);Console.Write("Minimum number of nodes to be removed to make "+"the tree complete is: ");// Function CallConsole.WriteLine(newSolution().MinNodesToBeRemoved(root));}}
JavaScript
// Javascript code for the above approach// Definition for a binary tree nodeclassTreeNode{constructor(val){this.val=val;this.left=null;this.right=null;}}// Function to calculate the height of the treefunctionheight(root){if(!root){return0;}return1+Math.max(height(root.left),height(root.right));}// dfs traversal to fill the arrayfunctiondfs(root,index,arr){if(!root){return;}arr[index]=root.val;dfs(root.left,2*index+1,arr);dfs(root.right,2*index+2,arr);}functionminNodesToBeRemoved_dfs(root){consth=height(root);// Find the size of the arrayconstmaxNodes=(1<<h)-1;// Make an array to store the nodes level wiseconstarr=newArray(maxNodes).fill(-1);// dfs calldfs(root,0,arr);letnullFound=false;letans=0;for(leti=0;i<arr.length;i++){constit=arr[i];// If the array value is -1// means node is nullif(it===-1){nullFound=true;}// If node is present after the// first null was found// increase the answerif(nullFound&&it!==-1){ans++;}}returnans;}// Drivers codefunctionmain(){/* * 1 * / \ * 2 3 * / \ \ * 4 5 6 * / \ * 7 8 * * Output: 3 */constroot=newTreeNode(1);root.left=newTreeNode(2);root.right=newTreeNode(3);root.left.left=newTreeNode(4);root.left.right=newTreeNode(5);root.right.right=newTreeNode(6);root.left.right.left=newTreeNode(7);root.left.right.right=newTreeNode(8);console.log("Minimum number of nodes to be removed to make "+"the tree complete is: "+minNodesToBeRemoved_dfs(root));}main();
Output
Minimum number of nodes to be removed to make the tree complete is: 3
Time Complexity: O(2^h-1), where h is the height of the tree. Auxiliary Space: O(2^h-1)