Given the root of a binary tree, find its maximum width. The maximum width of a binary tree is defined as the maximum number of nodes present at any level of the tree.
Example:
Input: root = [1, 2, 3, 4, 5, 6, 7]
Output: 4 Explanation: On the first level there is only one node [1]. On the second level there are two nodes [2, 3]. On the third level there are 4 nodes [4, 5, 6, 7], clearly it is the maximum number of nodes at any level.
Input: root = [10, 20, 30, 40, 60]
Output: 2 Explanation: There is one node on level 1(10) There is two node on level 2(20, 30) There is two node on level 3(40, 60) Hence the answer is 2
[Naive Approach] By Counting Nodes at Each Level- O(n^2) Time and O(h) Space
The idea is to first find the height of the tree, then for each level, count the number of nodes, and finally take the maximum of these counts as the width.
Call a helper function that counts nodes at that level.
Update the maximum width after checking each level.
C++
#include<iostream>#include<algorithm>usingnamespacestd;// Structure of a binary tree nodeclassNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=nullptr;right=nullptr;}};// Returns the height of the treeintheight(Node*root){if(root==nullptr)return0;return1+max(height(root->left),height(root->right));}// Counts nodes at the given levelintgetWidth(Node*root,intlevel){if(root==nullptr)return0;if(level==1)return1;returngetWidth(root->left,level-1)+getWidth(root->right,level-1);}// Returns the maximum width of the binary treeintmaxWidth(Node*root){inth=height(root);intans=0;for(inti=1;i<=h;i++){ans=max(ans,getWidth(root,i));}returnans;}intmain(){// root = [1, 2, 3, 4, 5, 6, 7]// Construct the following binary tree:// 1// / \ // 2 3// / \ / \ // 4 5 6 7Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(4);root->left->right=newNode(5);root->right->left=newNode(6);root->right->right=newNode(7);cout<<maxWidth(root)<<endl;return0;}
Java
// Structure of a binary tree nodeclassNode{intdata;Nodeleft;Noderight;Node(intx){data=x;left=null;right=null;}}classGFG{// Returns the height of the treepublicstaticintheight(Noderoot){if(root==null)return0;return1+Math.max(height(root.left),height(root.right));}// Counts nodes at the given levelpublicstaticintgetWidth(Noderoot,intlevel){if(root==null)return0;if(level==1)return1;returngetWidth(root.left,level-1)+getWidth(root.right,level-1);}// Returns the maximum width of the binary treepublicstaticintmaxWidth(Noderoot){inth=height(root);intans=0;for(inti=1;i<=h;i++){ans=Math.max(ans,getWidth(root,i));}returnans;}publicstaticvoidmain(String[]args){// root = [1, 2, 3, 4, 5, 6, 7]// Construct the following binary tree:// 1// / \// 2 3// / \ / \// 4 5 6 7Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);System.out.println(maxWidth(root));}}
Python
# Structure of a binary tree nodeclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Returns the height of the treedefheight(root):ifroot==None:return0return1+max(height(root.left),height(root.right))# Counts nodes at the given leveldefgetWidth(root,level):ifroot==None:return0iflevel==1:return1returngetWidth(root.left,level-1)+getWidth(root.right,level-1)# Returns the maximum width of the binary treedefmaxWidth(root):h=height(root)ans=0foriinrange(1,h+1):ans=max(ans,getWidth(root,i))returnansif__name__=="__main__":# root = [1, 2, 3, 4, 5, 6, 7]# Construct the following binary tree:# 1# / \# 2 3# / \ / \# 4 5 6 7root=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(4)root.left.right=Node(5)root.right.left=Node(6)root.right.right=Node(7)print(maxWidth(root))
C#
usingSystem;// Structure of a binary tree nodeclassNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intx){data=x;left=null;right=null;}}classGFG{// Returns the height of the treestaticintheight(Noderoot){if(root==null)return0;return1+Math.Max(height(root.left),height(root.right));}// Counts nodes at the given levelstaticintgetWidth(Noderoot,intlevel){if(root==null)return0;if(level==1)return1;returngetWidth(root.left,level-1)+getWidth(root.right,level-1);}// Returns the maximum width of the binary treestaticintmaxWidth(Noderoot){inth=height(root);intans=0;for(inti=1;i<=h;i++){ans=Math.Max(ans,getWidth(root,i));}returnans;}publicstaticvoidMain(){// root = [1, 2, 3, 4, 5, 6, 7]// Construct the following binary tree:// 1// / \// 2 3// / \ / \// 4 5 6 7Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);Console.WriteLine(maxWidth(root));}}
JavaScript
// Structure of a binary tree nodeclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Returns the height of the treefunctionheight(root){if(root==null)return0;return1+Math.max(height(root.left),height(root.right));}// Counts nodes at the given levelfunctiongetWidth(root,level){if(root==null)return0;if(level==1)return1;returngetWidth(root.left,level-1)+getWidth(root.right,level-1);}// Returns the maximum width of the binary treefunctionmaxWidth(root){leth=height(root);letans=0;for(leti=1;i<=h;i++){ans=Math.max(ans,getWidth(root,i));}returnans;}// Driver code// root = [1, 2, 3, 4, 5, 6, 7]// Construct the following binary tree:// 1// / \// 2 3// / \ / \// 4 5 6 7letroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);console.log(maxWidth(root));
Output
4
[Expected Approach 1] Using Level Order Traversal - O(n) Time and O(n) Space
The idea is to use level order traversal (BFS) and count the number of nodes at each level. The maximum count across all levels will be the width of the tree.
If root is NULL, return 0.
Insert the root node into a queue.
Traverse the tree level by level:
Get the number of nodes at the current level.
Update the maximum width.
Add children of current level nodes to the queue.
Return the maximum width.
C++
#include<iostream>#include<queue>#include<algorithm>usingnamespacestd;// Structure of a binary tree nodeclassNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=nullptr;right=nullptr;}};// Returns the maximum width of the binary treeintmaxWidth(Node*root){if(root==nullptr)return0;queue<Node*>q;q.push(root);intans=0;while(!q.empty()){// Number of nodes at current levelintcount=q.size();// Update maximum widthans=max(ans,count);// Process all nodes of current levelwhile(count--){Node*curr=q.front();q.pop();// Add left childif(curr->left)q.push(curr->left);// Add right childif(curr->right)q.push(curr->right);}}returnans;}intmain(){// root = [1, 2, 3, 4, 5, 6, 7]//// Construct the following binary tree:// 1// / \ // 2 3// / \ / \ // 4 5 6 7Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(4);root->left->right=newNode(5);root->right->left=newNode(6);root->right->right=newNode(7);cout<<maxWidth(root);return0;}
Java
importjava.util.Queue;importjava.util.LinkedList;// Structure of a binary tree nodeclassNode{intdata;Nodeleft;Noderight;Node(intx){data=x;left=null;right=null;}}classGFG{// Returns the maximum width of the binary treepublicstaticintmaxWidth(Noderoot){if(root==null)return0;Queue<Node>q=newLinkedList<>();q.add(root);intans=0;while(!q.isEmpty()){// Number of nodes at current levelintcount=q.size();// Update maximum widthans=Math.max(ans,count);// Process all nodes of current levelwhile(count-->0){Nodecurr=q.poll();// Add left childif(curr.left!=null)q.add(curr.left);// Add right childif(curr.right!=null)q.add(curr.right);}}returnans;}publicstaticvoidmain(String[]args){// root = [1, 2, 3, 4, 5, 6, 7]//// Construct the following binary tree:// 1// / \// 2 3// / \ / \// 4 5 6 7Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);System.out.println(maxWidth(root));}}
Python
fromcollectionsimportdeque# Structure of a binary tree nodeclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Returns the maximum width of the binary treedefmaxWidth(root):ifroot==None:return0q=deque()q.append(root)ans=0whilelen(q)>0:# Number of nodes at current levelcount=len(q)# Update maximum widthans=max(ans,count)# Process all nodes of current levelwhilecount>0:curr=q.popleft()count-=1# Add left childifcurr.left:q.append(curr.left)# Add right childifcurr.right:q.append(curr.right)returnansif__name__=="__main__":# root = [1, 2, 3, 4, 5, 6, 7]## Construct the following binary tree:# 1# / \# 2 3# / \ / \# 4 5 6 7root=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(4)root.left.right=Node(5)root.right.left=Node(6)root.right.right=Node(7)print(maxWidth(root))
C#
usingSystem;usingSystem.Collections.Generic;// Structure of a binary tree nodeclassNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intx){data=x;left=null;right=null;}}classGFG{// Returns the maximum width of the binary treepublicstaticintmaxWidth(Noderoot){if(root==null)return0;Queue<Node>q=newQueue<Node>();q.Enqueue(root);intans=0;while(q.Count>0){// Number of nodes at current levelintcount=q.Count;// Update maximum widthans=Math.Max(ans,count);// Process all nodes of current levelwhile(count-->0){Nodecurr=q.Dequeue();// Add left childif(curr.left!=null)q.Enqueue(curr.left);// Add right childif(curr.right!=null)q.Enqueue(curr.right);}}returnans;}publicstaticvoidMain(){// root = [1, 2, 3, 4, 5, 6, 7]//// Construct the following binary tree:// 1// / \// 2 3// / \ / \// 4 5 6 7Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);Console.WriteLine(maxWidth(root));}}
JavaScript
// Structure of a binary tree nodeclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Returns the maximum width of the binary treefunctionmaxWidth(root){if(root==null)return0;letq=[];q.push(root);letans=0;while(q.length>0){// Number of nodes at current levelletcount=q.length;// Update maximum widthans=Math.max(ans,count);// Process all nodes of current levelwhile(count-->0){letcurr=q.shift();// Add left childif(curr.left)q.push(curr.left);// Add right childif(curr.right)q.push(curr.right);}}returnans;}// Driver code// root = [1, 2, 3, 4, 5, 6, 7]//// Construct the following binary tree:// 1// / \// 2 3// / \ / \// 4 5 6 7letroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);console.log(maxWidth(root));
Output
4
[Expected Approach 2] Using Preorder Traversal - O(n) Time and O(n) Space
Instead of traversing the tree level by level, we can count nodes at each level using a preorder traversal. Maintain an array count, where the index represents the level of the tree and the value stores the number of nodes present at that level. During preorder traversal, whenever we visit a node, we increase the count of its corresponding level.
After visiting all nodes, the maximum value in the count array represents the maximum width of the binary tree.
Create a temporary array count of size equal to the height of the tree.
Initialize all values in count as 0.
Traverse the tree using preorder traversal and fill the entries in count so that
The count array contains the count of nodes at each level of the Binary Tree.
The level with the maximum number of nodes has the maximum width.
Return the value of that level.
C++
#include<iostream>#include<vector>#include<algorithm>usingnamespacestd;// Structure of a binary tree nodeclassNode{public:intdata;Node*left;Node*right;Node(intx){data=x;left=nullptr;right=nullptr;}};// Preorder traversal to count nodes at each levelvoidpreorder(Node*root,intlevel,vector<int>&count){if(root==nullptr)return;// Add new level in count arrayif(level==count.size())count.push_back(0);// Increase count of nodes at current levelcount[level]++;// Traverse left subtreepreorder(root->left,level+1,count);// Traverse right subtreepreorder(root->right,level+1,count);}// Returns the maximum width of the binary treeintmaxWidth(Node*root){vector<int>count;// Store number of nodes at each levelpreorder(root,0,count);intans=0;// Find maximum count among all levelsfor(intx:count){ans=max(ans,x);}returnans;}intmain(){// root = [1, 2, 3, 4, 5, 6, 7]//// Construct the following binary tree:// 1// / \ // 2 3// / \ / \ // 4 5 6 7Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(4);root->left->right=newNode(5);root->right->left=newNode(6);root->right->right=newNode(7);cout<<maxWidth(root);return0;}
Java
importjava.util.ArrayList;// Structure of a binary tree nodeclassNode{intdata;Nodeleft;Noderight;Node(intx){data=x;left=null;right=null;}}classGFG{// Preorder traversal to count nodes at each levelpublicstaticvoidpreorder(Noderoot,intlevel,ArrayList<Integer>count){if(root==null)return;// Add new level in count arrayif(level==count.size())count.add(0);// Increase count of nodes at current levelcount.set(level,count.get(level)+1);// Traverse left subtreepreorder(root.left,level+1,count);// Traverse right subtreepreorder(root.right,level+1,count);}// Returns the maximum width of the binary treepublicstaticintmaxWidth(Noderoot){ArrayList<Integer>count=newArrayList<>();// Store number of nodes at each levelpreorder(root,0,count);intans=0;// Find maximum count among all levelsfor(intx:count){ans=Math.max(ans,x);}returnans;}publicstaticvoidmain(String[]args){// root = [1, 2, 3, 4, 5, 6, 7]//// Construct the following binary tree:// 1// / \// 2 3// / \ / \// 4 5 6 7Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);System.out.println(maxWidth(root));}}
Python
# Structure of a binary tree nodeclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Preorder traversal to count nodes at each leveldefpreorder(root,level,count):ifroot==None:return# Add new level in count arrayiflevel==len(count):count.append(0)# Increase count of nodes at current levelcount[level]+=1# Traverse left subtreepreorder(root.left,level+1,count)# Traverse right subtreepreorder(root.right,level+1,count)# Returns the maximum width of the binary treedefmaxWidth(root):count=[]# Store number of nodes at each levelpreorder(root,0,count)ans=0# Find maximum count among all levelsforxincount:ans=max(ans,x)returnansif__name__=="__main__":# root = [1, 2, 3, 4, 5, 6, 7]## Construct the following binary tree:# 1# / \# 2 3# / \ / \# 4 5 6 7root=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(4)root.left.right=Node(5)root.right.left=Node(6)root.right.right=Node(7)print(maxWidth(root))
C#
usingSystem;usingSystem.Collections.Generic;// Structure of a binary tree nodeclassNode{publicintdata;publicNodeleft;publicNoderight;publicNode(intx){data=x;left=null;right=null;}}classGFG{// Preorder traversal to count nodes at each levelpublicstaticvoidpreorder(Noderoot,intlevel,List<int>count){if(root==null)return;// Add new level in count arrayif(level==count.Count)count.Add(0);// Increase count of nodes at current levelcount[level]++;// Traverse left subtreepreorder(root.left,level+1,count);// Traverse right subtreepreorder(root.right,level+1,count);}// Returns the maximum width of the binary treepublicstaticintmaxWidth(Noderoot){List<int>count=newList<int>();// Store number of nodes at each levelpreorder(root,0,count);intans=0;// Find maximum count among all levelsforeach(intxincount){ans=Math.Max(ans,x);}returnans;}publicstaticvoidMain(){// root = [1, 2, 3, 4, 5, 6, 7]//// Construct the following binary tree:// 1// / \// 2 3// / \ / \// 4 5 6 7Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);Console.WriteLine(maxWidth(root));}}
JavaScript
// Structure of a binary tree nodeclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Preorder traversal to count nodes at each levelfunctionpreorder(root,level,count){if(root==null)return;// Add new level in count arrayif(level==count.length)count.push(0);// Increase count of nodes at current levelcount[level]++;// Traverse left subtreepreorder(root.left,level+1,count);// Traverse right subtreepreorder(root.right,level+1,count);}// Returns the maximum width of the binary treefunctionmaxWidth(root){letcount=[];// Store number of nodes at each levelpreorder(root,0,count);letans=0;// Find maximum count among all levelsfor(letxofcount){ans=Math.max(ans,x);}returnans;}// Driver code// root = [1, 2, 3, 4, 5, 6, 7]// Construct the following binary tree:// 1// / \// 2 3// / \ / \// 4 5 6 7letroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.left=newNode(6);root.right.right=newNode(7);console.log(maxWidth(root));