Given a binary tree, the task is to find the level in a binary tree that has the maximum number of nodes.
Note: The root is at level 0.
Examples:
Input: Binary Tree
Output : 2 Explanation:
Input: Binary tree
Output:1 Explanation
Using Breadth First Search - O(n) time and O(n) space
The idea is to traverse the binary tree level by level, keeping track of the number of nodes at each level. As we process each level, we compare its node count with the maximum count found so far, updating our result level if the current level has more nodes. The queue-based BFS naturally groups nodes by their level, making it straightforward to count nodes per level.
Step by step approach:
Start with root node in the queue and initialize tracking variables for level, max nodes, and result level.
For each level, record its size (number of nodes) from the queue before processing.
If current level's size exceeds previous maximum, update the maximum count and result level.
Process all nodes at current level, adding their children to queue for next level processing.
Return the level that had the maximum number of nodes after all levels are processed.
C++
// C++ code to find Level with maximum number of nodes using BFS#include<iostream>#include<queue>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=nullptr;right=nullptr;}};intmaxNodeLevel(Node*root){if(root==nullptr)return-1;queue<Node*>q;q.push(root);intlevel=0;intmaxNodes=0;intmaxLevel=0;while(!q.empty()){// Number of nodes at current levelintsize=q.size();if(size>maxNodes){maxNodes=size;maxLevel=level;}// Process all nodes at current levelfor(inti=0;i<size;i++){Node*current=q.front();q.pop();if(current->left)q.push(current->left);if(current->right)q.push(current->right);}level++;}returnmaxLevel;}intmain(){// 2// / \ // 1 3// / \ \ // 4 6 8// /// 5Node*root=newNode(2);root->left=newNode(1);root->right=newNode(3);root->left->left=newNode(4);root->left->right=newNode(6);root->right->right=newNode(8);root->left->left->left=newNode(5);cout<<maxNodeLevel(root)<<endl;return0;}
Java
// Java code to find Level with maximum number of nodes using BFSimportjava.util.Queue;importjava.util.LinkedList;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=null;right=null;}}classGfG{// A function to find level with maximum number of nodesstaticintmaxNodeLevel(Noderoot){if(root==null)return-1;Queue<Node>q=newLinkedList<>();q.add(root);intlevel=0;intmaxNodes=0;intmaxLevel=0;while(!q.isEmpty()){// Number of nodes at current levelintsize=q.size();if(size>maxNodes){maxNodes=size;maxLevel=level;}// Process all nodes at current levelfor(inti=0;i<size;i++){Nodecurrent=q.poll();if(current.left!=null)q.add(current.left);if(current.right!=null)q.add(current.right);}level++;}returnmaxLevel;}publicstaticvoidmain(String[]args){// 2// / \// 1 3// / \ \// 4 6 8// /// 5Noderoot=newNode(2);root.left=newNode(1);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(6);root.right.right=newNode(8);root.left.left.left=newNode(5);System.out.println(maxNodeLevel(root));}}
Python
# Python code to find Level with maximum number of nodes using BFSfromcollectionsimportdequeclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# A function to find level with maximum number of nodesdefmaxNodeLevel(root):ifrootisNone:return-1q=deque()q.append(root)level=0maxNodes=0maxLevel=0whileq:# Number of nodes at current levelsize=len(q)ifsize>maxNodes:maxNodes=sizemaxLevel=level# Process all nodes at current levelfor_inrange(size):current=q.popleft()ifcurrent.left:q.append(current.left)ifcurrent.right:q.append(current.right)level+=1returnmaxLevelif__name__=="__main__":# 2# / \# 1 3# / \ \# 4 6 8# /# 5root=Node(2)root.left=Node(1)root.right=Node(3)root.left.left=Node(4)root.left.right=Node(6)root.right.right=Node(8)root.left.left.left=Node(5)print(maxNodeLevel(root))
C#
// C# code to find Level with maximum number of nodes using BFSusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=null;right=null;}}classGfG{// A function to find level with maximum number of nodesstaticintmaxNodeLevel(Noderoot){if(root==null)return-1;Queue<Node>q=newQueue<Node>();q.Enqueue(root);intlevel=0;intmaxNodes=0;intmaxLevel=0;while(q.Count>0){// Number of nodes at current levelintsize=q.Count;if(size>maxNodes){maxNodes=size;maxLevel=level;}// Process all nodes at current levelfor(inti=0;i<size;i++){Nodecurrent=q.Dequeue();if(current.left!=null)q.Enqueue(current.left);if(current.right!=null)q.Enqueue(current.right);}level++;}returnmaxLevel;}staticvoidMain(string[]args){// 2// / \// 1 3// / \ \// 4 6 8// /// 5Noderoot=newNode(2);root.left=newNode(1);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(6);root.right.right=newNode(8);root.left.left.left=newNode(5);Console.WriteLine(maxNodeLevel(root));}}
JavaScript
// JavaScript code to find Level with maximum number of nodes using BFSclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// A function to find level with maximum number of nodesfunctionmaxNodeLevel(root){if(root===null)return-1;letq=[];q.push(root);letlevel=0;letmaxNodes=0;letmaxLevel=0;while(q.length>0){// Number of nodes at current levelletsize=q.length;if(size>maxNodes){maxNodes=size;maxLevel=level;}// Process all nodes at current levelfor(leti=0;i<size;i++){letcurrent=q.shift();if(current.left!==null)q.push(current.left);if(current.right!==null)q.push(current.right);}level++;}returnmaxLevel;}// 2// / \// 1 3// / \ \// 4 6 8// /// 5letroot=newNode(2);root.left=newNode(1);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(6);root.right.right=newNode(8);root.left.left.left=newNode(5);console.log(maxNodeLevel(root));
Output
2
Using Depth First Search - O(n) time and O(n) space
The idea is to use depth-first traversal to visit each node while keeping track of its level, storing the count of nodes for each level in a hash map. As we traverse the tree recursively, we increment the counter for the current level in our map. After the entire tree is traversed, we simply identify which level has the highest node count.
Step by step approach:
Create a hash map to store the count of nodes for each level.
Perform DFS recursively, passing the current level information to each call.
For each node visited, increment the count for its level in the hash map.
After full traversal, iterate through the hash map to find the level with maximum nodes.
Return the level that has the highest node count.
C++
// C++ code to find Level with maximum number of nodes using DFS#include<iostream>#include<unordered_map>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=nullptr;right=nullptr;}};// Helper function for DFSvoiddfs(Node*root,intlevel,unordered_map<int,int>&levelCount){if(root==nullptr)return;// Increment count of nodes at current levellevelCount[level]++;// Recursively process left and right subtreesdfs(root->left,level+1,levelCount);dfs(root->right,level+1,levelCount);}intmaxNodeLevel(Node*root){if(root==nullptr)return-1;// Map to store count of nodes at each levelunordered_map<int,int>levelCount;// Perform DFS to count nodes at each leveldfs(root,0,levelCount);intmaxNodes=0;intmaxLevel=0;// Find the level with maximum nodesfor(auto&pair:levelCount){intlevel=pair.first;intcount=pair.second;if(count>maxNodes){maxNodes=count;maxLevel=level;}}returnmaxLevel;}intmain(){// 2// / \ // 1 3// / \ \ // 4 6 8// /// 5Node*root=newNode(2);root->left=newNode(1);root->right=newNode(3);root->left->left=newNode(4);root->left->right=newNode(6);root->right->right=newNode(8);root->left->left->left=newNode(5);cout<<maxNodeLevel(root)<<endl;return0;}
Java
// Java code to find Level with maximum number of nodes using DFSimportjava.util.*;classNode{intdata;Nodeleft,right;Node(intx){data=x;left=null;right=null;}}classGfG{// Helper function for DFSstaticvoiddfs(Noderoot,intlevel,HashMap<Integer,Integer>levelCount){if(root==null)return;// Increment count of nodes at current levellevelCount.put(level,levelCount.getOrDefault(level,0)+1);// Recursively process left and right subtreesdfs(root.left,level+1,levelCount);dfs(root.right,level+1,levelCount);}staticintmaxNodeLevel(Noderoot){if(root==null)return-1;// Map to store count of nodes at each levelHashMap<Integer,Integer>levelCount=newHashMap<>();// Perform DFS to count nodes at each leveldfs(root,0,levelCount);intmaxNodes=0;intmaxLevel=0;// Find the level with maximum nodesfor(Map.Entry<Integer,Integer>pair:levelCount.entrySet()){intlevel=pair.getKey();intcount=pair.getValue();if(count>maxNodes){maxNodes=count;maxLevel=level;}}returnmaxLevel;}publicstaticvoidmain(String[]args){// 2// / \// 1 3// / \ \// 4 6 8// /// 5Noderoot=newNode(2);root.left=newNode(1);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(6);root.right.right=newNode(8);root.left.left.left=newNode(5);System.out.println(maxNodeLevel(root));}}
Python
# Python code to find Level with maximum number of nodes using DFSfromcollectionsimportdefaultdictclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Helper function for DFSdefdfs(root,level,levelCount):ifrootisNone:return# Increment count of nodes at current levellevelCount[level]+=1# Recursively process left and right subtreesdfs(root.left,level+1,levelCount)dfs(root.right,level+1,levelCount)defmaxNodeLevel(root):ifrootisNone:return-1# Map to store count of nodes at each levellevelCount=defaultdict(int)# Perform DFS to count nodes at each leveldfs(root,0,levelCount)maxNodes=0maxLevel=0# Find the level with maximum nodesforlevelinlevelCount:count=levelCount[level]ifcount>maxNodes:maxNodes=countmaxLevel=levelreturnmaxLevelif__name__=="__main__":# 2# / \# 1 3# / \ \# 4 6 8# /# 5root=Node(2)root.left=Node(1)root.right=Node(3)root.left.left=Node(4)root.left.right=Node(6)root.right.right=Node(8)root.left.left.left=Node(5)print(maxNodeLevel(root))
C#
// C# code to find Level with maximum number of nodes using DFSusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=null;right=null;}}classGfG{// Helper function for DFSstaticvoiddfs(Noderoot,intlevel,Dictionary<int,int>levelCount){if(root==null)return;// Increment count of nodes at current levelif(!levelCount.ContainsKey(level))levelCount[level]=0;levelCount[level]++;// Recursively process left and right subtreesdfs(root.left,level+1,levelCount);dfs(root.right,level+1,levelCount);}staticintmaxNodeLevel(Noderoot){if(root==null)return-1;// Map to store count of nodes at each levelDictionary<int,int>levelCount=newDictionary<int,int>();// Perform DFS to count nodes at each leveldfs(root,0,levelCount);intmaxNodes=0;intmaxLevel=0;// Find the level with maximum nodesforeach(varpairinlevelCount){intlevel=pair.Key;intcount=pair.Value;if(count>maxNodes){maxNodes=count;maxLevel=level;}}returnmaxLevel;}staticvoidMain(string[]args){// 2// / \// 1 3// / \ \// 4 6 8// /// 5Noderoot=newNode(2);root.left=newNode(1);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(6);root.right.right=newNode(8);root.left.left.left=newNode(5);Console.WriteLine(maxNodeLevel(root));}}
JavaScript
// JavaScript code to find Level with maximum number of nodes using DFSclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Helper function for DFSfunctiondfs(root,level,levelCount){if(root===null)return;// Increment count of nodes at current levelif(!levelCount.has(level)){levelCount.set(level,0);}levelCount.set(level,levelCount.get(level)+1);// Recursively process left and right subtreesdfs(root.left,level+1,levelCount);dfs(root.right,level+1,levelCount);}functionmaxNodeLevel(root){if(root===null)return-1;// Map to store count of nodes at each levelconstlevelCount=newMap();// Perform DFS to count nodes at each leveldfs(root,0,levelCount);letmaxNodes=0;letmaxLevel=0;// Find the level with maximum nodesfor(let[level,count]oflevelCount.entries()){if(count>maxNodes){maxNodes=count;maxLevel=level;}}returnmaxLevel;}// 2// / \// 1 3// / \ \// 4 6 8// /// 5letroot=newNode(2);root.left=newNode(1);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(6);root.right.right=newNode(8);root.left.left.left=newNode(5);console.log(maxNodeLevel(root));
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.