Count of leaf nodes required to be removed at each step to empty a given Binary Tree
Last Updated : 23 Jun, 2026
Given the root of a binary tree of size n, repeatedly remove all leaf nodes in each operation and return an array containing the count of leaf nodes removed at every step.
Examples:
Input:
Output: 4 2 1 1 Explanation: In the 1st operation removing the leaf nodes { 1, 3, 4, 6 } from the binary tree. In the 2nd operation removing the leaf nodes { 8, 7 } In the 3rd operation removing the leaf nodes { 5 } In the 4th operation removing the leaf nodes { 2 } Therefore, the count of leaf nodes removed in each operation 4 2 1 1.
Input:
Output: 2 1 Explanation: In the 1st operation, leaf nodes {3,2} are removed. In the 2nd operation, leaf nodes {1} are removed. Therefore, the count of leaf nodes removed in each operation is 2 1.
[Naive Approach] Repeated DFS Simulation for Leaf Removal - O(n^2) Time and O(h) Space
The idea is to repeatedly remove all leaf nodes from the binary tree and record their count at each step. In each iteration, we traverse the tree, delete current leaf nodes, and update the structure. Since removing leaves creates new leaves, the process continues until the tree becomes empty. Finally, we return the count of nodes removed in each iteration.
C++
#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intval){data=val;left=right=nullptr;}};// Helper function to remove all leaf nodes in one passNode*removeLeaves(Node*root,int&cnt){if(!root)returnnullptr;// If current node is a leafif(!root->left&&!root->right){cnt++;deleteroot;returnnullptr;}root->left=removeLeaves(root->left,cnt);root->right=removeLeaves(root->right,cnt);returnroot;}vector<int>emptyTree(Node*root){vector<int>ans;while(root){intcnt=0;root=removeLeaves(root,cnt);ans.push_back(cnt);}returnans;}intmain(){// Tree structure:// 2// / \ // 5 7// / \ \ // 1 8 6// / \ // 3 4Node*root=newNode(2);root->left=newNode(5);root->right=newNode(7);root->right->right=newNode(6);root->left->left=newNode(1);root->left->right=newNode(8);root->left->right->left=newNode(3);root->left->right->right=newNode(4);vector<int>res=emptyTree(root);for(intx:res){cout<<x<<" ";}return0;}
Java
importjava.util.ArrayList;classNode{intdata;Nodeleft;Noderight;Node(intval){data=val;left=right=null;}}publicclassGFG{// Helper function to remove all leaf nodes in one passstaticNoderemoveLeaves(Noderoot,int[]cnt){if(root==null)returnnull;// If current node is a leafif(root.left==null&&root.right==null){cnt[0]++;returnnull;}root.left=removeLeaves(root.left,cnt);root.right=removeLeaves(root.right,cnt);returnroot;}staticArrayList<Integer>emptyTree(Noderoot){ArrayList<Integer>ans=newArrayList<>();while(root!=null){int[]cnt=newint[1];root=removeLeaves(root,cnt);ans.add(cnt[0]);}returnans;}publicstaticvoidmain(String[]args){// Tree structure:// 2// / \// 5 7// / \ \// 1 8 6// / \// 3 4Noderoot=newNode(2);root.left=newNode(5);root.right=newNode(7);root.right.right=newNode(6);root.left.left=newNode(1);root.left.right=newNode(8);root.left.right.left=newNode(3);root.left.right.right=newNode(4);ArrayList<Integer>res=emptyTree(root);for(intx:res){System.out.print(x+" ");}}}
Python
classNode:def__init__(self,val):self.data=valself.left=Noneself.right=None# Helper function to remove all leaf nodes in one passdefremoveLeaves(root,cnt):ifnotroot:returnNone# If current node is a leafifnotroot.leftandnotroot.right:cnt[0]+=1returnNoneroot.left=removeLeaves(root.left,cnt)root.right=removeLeaves(root.right,cnt)returnrootdefemptyTree(root):ans=[]whileroot:cnt=[0]root=removeLeaves(root,cnt)ans.append(cnt[0])returnansif__name__=="__main__":# Tree structure:# 2# / \# 5 7# / \ \# 1 8 6# / \# 3 4root=Node(2)root.left=Node(5)root.right=Node(7)root.right.right=Node(6)root.left.left=Node(1)root.left.right=Node(8)root.left.right.left=Node(3)root.left.right.right=Node(4)res=emptyTree(root)forxinres:print(x,end=" ")
C#
usingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intval){data=val;left=right=null;}}classGFG{// Helper function to remove all leaf nodes in one passstaticNoderemoveLeaves(Noderoot,refintcnt){if(root==null)returnnull;// If current node is a leafif(root.left==null&&root.right==null){cnt++;returnnull;}root.left=removeLeaves(root.left,refcnt);root.right=removeLeaves(root.right,refcnt);returnroot;}staticList<int>emptyTree(Noderoot){List<int>ans=newList<int>();while(root!=null){intcnt=0;root=removeLeaves(root,refcnt);ans.Add(cnt);}returnans;}staticvoidMain(string[]args){// Tree structure:// 2// / \// 5 7// / \ \// 1 8 6// / \// 3 4Noderoot=newNode(2);root.left=newNode(5);root.right=newNode(7);root.right.right=newNode(6);root.left.left=newNode(1);root.left.right=newNode(8);root.left.right.left=newNode(3);root.left.right.right=newNode(4);List<int>res=emptyTree(root);foreach(intxinres){Console.Write(x+" ");}}}
JavaScript
classNode{constructor(val){this.data=val;this.left=null;this.right=null;}}// Helper function to remove all leaf nodes in one passfunctionremoveLeaves(root,cnt){if(root===null)returnnull;// If current node is a leafif(root.left===null&&root.right===null){cnt.count++;returnnull;}root.left=removeLeaves(root.left,cnt);root.right=removeLeaves(root.right,cnt);returnroot;}functionemptyTree(root){letans=[];while(root!==null){letcnt={count:0};root=removeLeaves(root,cnt);ans.push(cnt.count);}returnans;}// Driver code// Tree structure:// 2// / \// 5 7// / \ \// 1 8 6// / \// 3 4letroot=newNode(2);root.left=newNode(5);root.right=newNode(7);root.right.right=newNode(6);root.left.left=newNode(1);root.left.right=newNode(8);root.left.right.left=newNode(3);root.left.right.right=newNode(4);letres=emptyTree(root);console.log(res.join(" "));
Output
4 2 1 1
[Expected Approach] Group Nodes by Height Using DFS Traversal - O(n) Time and O(n) Space
Instead of repeatedly removing leaf nodes, we observe that each node is deleted based on its height from the bottom (leaf level). All nodes with the same height are removed in the same operation.
So, we compute the height of each node using DFS and group nodes by height. The size of each group gives the number of nodes removed in each step.
Traverse the binary tree using DFS.
For each node, compute its height as: height = 1 + max(leftHeight, rightHeight)
Store nodes in a map where: Key is height and Value is list of nodes at that height
Iterate the map in increasing order of height.
For each group, add its size to the result array.
C++
#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node(intval){data=val;left=right=nullptr;}};// Returns the height of the current node// and groups nodes having the same height.intgetHeight(Node*root,map<int,vector<int>>&mp){if(root==nullptr)return0;// Height of left subtreeintlh=getHeight(root->left,mp);// Height of right subtreeintrh=getHeight(root->right,mp);// Height of current nodeintht=1+max(lh,rh);// Store current node at its height levelmp[ht].push_back(root->data);returnht;}vector<int>emptyTree(Node*root){// Stores the number of nodes removed// in each iterationvector<int>res;// Maps height -> nodes at that heightmap<int,vector<int>>mp;// Group nodes by heightgetHeight(root,mp);// Nodes with the same height are removed// in the same iterationfor(auto&it:mp){res.push_back(it.second.size());}returnres;}intmain(){// Tree structure:// 2// / \ // 5 7// / \ \ // 1 8 6// / \ // 3 4Node*root=newNode(2);root->left=newNode(5);root->right=newNode(7);root->right->right=newNode(6);root->left->left=newNode(1);root->left->right=newNode(8);root->left->right->left=newNode(3);root->left->right->right=newNode(4);vector<int>res=emptyTree(root);for(intx:res){cout<<x<<" ";}return0;}
Java
importjava.util.ArrayList;importjava.util.Map;importjava.util.TreeMap;classNode{intdata;Nodeleft;Noderight;Node(intval){data=val;left=right=null;}}publicclassGFG{// Returns the height of the current node// and groups nodes having the same height.staticintgetHeight(Noderoot,Map<Integer,ArrayList<Integer>>mp){if(root==null)return0;// Height of left subtreeintlh=getHeight(root.left,mp);// Height of right subtreeintrh=getHeight(root.right,mp);// Height of current nodeintht=1+Math.max(lh,rh);// Store current node at its height levelmp.putIfAbsent(ht,newArrayList<>());mp.get(ht).add(root.data);returnht;}staticArrayList<Integer>emptyTree(Noderoot){// Stores the number of nodes removed// in each iterationArrayList<Integer>res=newArrayList<>();// Maps height -> nodes at that heightMap<Integer,ArrayList<Integer>>mp=newTreeMap<>();// Group nodes by heightgetHeight(root,mp);// Nodes with the same height are removed// in the same iterationfor(Map.Entry<Integer,ArrayList<Integer>>it:mp.entrySet()){res.add(it.getValue().size());}returnres;}publicstaticvoidmain(String[]args){// Tree structure:// 2// / \// 5 7// / \ \// 1 8 6// / \// 3 4Noderoot=newNode(2);root.left=newNode(5);root.right=newNode(7);root.right.right=newNode(6);root.left.left=newNode(1);root.left.right=newNode(8);root.left.right.left=newNode(3);root.left.right.right=newNode(4);ArrayList<Integer>res=emptyTree(root);for(intx:res){System.out.print(x+" ");}}}
Python
classNode:def__init__(self,val):self.data=valself.left=Noneself.right=None# Returns the height of the current node# and groups nodes having the same height.defgetHeight(root,mp):ifrootisNone:return0# Height of left subtreelh=getHeight(root.left,mp)# Height of right subtreerh=getHeight(root.right,mp)# Height of current nodeht=1+max(lh,rh)# Store current node at its height levelifhtnotinmp:mp[ht]=[]mp[ht].append(root.data)returnhtdefemptyTree(root):# Stores the number of nodes removed# in each iterationres=[]# Maps height -> nodes at that heightmp={}# Group nodes by heightgetHeight(root,mp)# Nodes with the same height are removed# in the same iterationforkeyinsorted(mp.keys()):res.append(len(mp[key]))returnresif__name__=="__main__":# Tree structure:# 2# / \# 5 7# / \ \# 1 8 6# / \# 3 4root=Node(2)root.left=Node(5)root.right=Node(7)root.right.right=Node(6)root.left.left=Node(1)root.left.right=Node(8)root.left.right.left=Node(3)root.left.right.right=Node(4)res=emptyTree(root)forxinres:print(x,end=" ")
C#
usingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intval){data=val;left=right=null;}}classGFG{// Returns the height of the current node// and groups nodes having the same height.staticintgetHeight(Noderoot,Dictionary<int,List<int>>mp){if(root==null)return0;// Height of left subtreeintlh=getHeight(root.left,mp);// Height of right subtreeintrh=getHeight(root.right,mp);// Height of current nodeintht=1+Math.Max(lh,rh);// Store current node at its height levelif(!mp.ContainsKey(ht))mp[ht]=newList<int>();mp[ht].Add(root.data);returnht;}staticList<int>emptyTree(Noderoot){// Stores the number of nodes removed// in each iterationList<int>res=newList<int>();// Maps height -> nodes at that heightDictionary<int,List<int>>mp=newDictionary<int,List<int>>();// Group nodes by heightgetHeight(root,mp);// Nodes with the same height are removed// in the same iterationforeach(varitinmp){res.Add(it.Value.Count);}returnres;}staticvoidMain(){// Tree structure:// 2// / \// 5 7// / \ \// 1 8 6// / \// 3 4Noderoot=newNode(2);root.left=newNode(5);root.right=newNode(7);root.right.right=newNode(6);root.left.left=newNode(1);root.left.right=newNode(8);root.left.right.left=newNode(3);root.left.right.right=newNode(4);List<int>res=emptyTree(root);foreach(intxinres){Console.Write(x+" ");}}}
JavaScript
classNode{constructor(val){this.data=val;this.left=null;this.right=null;}}// Returns the height of the current node// and groups nodes having the same height.functiongetHeight(root,mp){if(root===null)return0;// Height of left subtreeletlh=getHeight(root.left,mp);// Height of right subtreeletrh=getHeight(root.right,mp);// Height of current nodeletht=1+Math.max(lh,rh);// Store current node at its height levelif(!mp.has(ht))mp.set(ht,[]);mp.get(ht).push(root.data);returnht;}functionemptyTree(root){// Stores the number of nodes removed// in each iterationletres=[];// Maps height -> nodes at that heightletmp=newMap();// Group nodes by heightgetHeight(root,mp);// Nodes with the same height are removed// in the same iterationfor(let[key,value]of[...mp.entries()].sort((a,b)=>a[0]-b[0])){res.push(value.length);}returnres;}// Driver code// Tree structure:// 2// / \// 5 7// / \ \// 1 8 6// / \// 3 4letroot=newNode(2);root.left=newNode(5);root.right=newNode(7);root.right.right=newNode(6);root.left.left=newNode(1);root.left.right=newNode(8);root.left.right.left=newNode(3);root.left.right.right=newNode(4);letres=emptyTree(root);console.log(res.join(" "));