Given a binary tree, we need to find its maximum width. The width of a binary tree is defined as the maximum number of nodes present at any level of the tree.
Example:
Input:
Output: 3 Explanation: For the tree width is considered as number of nodes in that level , width of level 1 is 1, width of level 2 is 2, width of level 3 is 3 width of level 4 is 2. So the maximum width of the tree is 3.
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<queue>usingnamespacestd;/* A binary tree node has data, pointer to left childand a pointer to right child */classnode{public:intdata;node*left;node*right;node(intd){this->data=d;this->left=this->right=NULL;}};/*Function prototypes*/intgetWidth(node*root,intlevel);intheight(node*node);/* Function to get the maximum width of a binary tree*/intgetMaxWidth(node*root){intmaxWidth=0;intwidth;inth=height(root);inti;/* Get width of each level and compare the width with maximum width so far */for(i=1;i<=h;i++){width=getWidth(root,i);if(width>maxWidth)maxWidth=width;}returnmaxWidth;}/* Get width of a given level */intgetWidth(node*root,intlevel){if(root==NULL)return0;if(level==1)return1;elseif(level>1)returngetWidth(root->left,level-1)+getWidth(root->right,level-1);}/* UTILITY FUNCTIONS *//* Compute the "height" of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node.*/intheight(node*node){if(node==NULL)return0;else{/* compute the height of each subtree */intlHeight=height(node->left);intrHeight=height(node->right);/* use the larger one */return(lHeight>rHeight)?(lHeight+1):(rHeight+1);}}/* Driver code*/intmain(){node*root=newnode(1);root->left=newnode(2);root->right=newnode(3);root->left->left=newnode(4);root->left->right=newnode(5);root->right->right=newnode(8);root->right->right->left=newnode(6);root->right->right->right=newnode(7);/* Constructed binary tree is: 1 / \ 2 3 / \ \ 4 5 8 / \ 6 7 */// Function callcout<<getMaxWidth(root)<<endl;return0;}
C
// C program to calculate width of binary tree#include<stdio.h>#include<stdlib.h>/* A binary tree node has data, pointer to left child and a pointer to right child */structnode{intdata;structnode*left;structnode*right;};/*Function prototypes*/intgetWidth(structnode*root,intlevel);intheight(structnode*node);structnode*newNode(intdata);/* Function to get the maximum width of a binary tree*/intgetMaxWidth(structnode*root){intmaxWidth=0;intwidth;inth=height(root);inti;/* Get width of each level and compare the width with maximum width so far */for(i=1;i<=h;i++){width=getWidth(root,i);if(width>maxWidth)maxWidth=width;}returnmaxWidth;}/* Get width of a given level */intgetWidth(structnode*root,intlevel){if(root==NULL)return0;if(level==1)return1;elseif(level>1)returngetWidth(root->left,level-1)+getWidth(root->right,level-1);}/* UTILITY FUNCTIONS *//* Compute the "height" of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node.*/intheight(structnode*node){if(node==NULL)return0;else{/* compute the height of each subtree */intlHeight=height(node->left);intrHeight=height(node->right);/* use the larger one */return(lHeight>rHeight)?(lHeight+1):(rHeight+1);}}/* Helper function that allocates a new node with the given data and NULL left and right pointers. */structnode*newNode(intdata){structnode*node=(structnode*)malloc(sizeof(structnode));node->data=data;node->left=NULL;node->right=NULL;return(node);}/* Driver code*/intmain(){structnode*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(4);root->left->right=newNode(5);root->right->right=newNode(8);root->right->right->left=newNode(6);root->right->right->right=newNode(7);/* Constructed binary tree is: 1 / \ 2 3 / \ \ 4 5 8 / \ 6 7 */// Function callprintf("%d \n",getMaxWidth(root));getchar();return0;}
Java
classNode{intdata;Nodeleft,right;Node(intitem){data=item;left=right=null;}}classBinaryTree{Noderoot;/* Function to get the maximum width of a binary tree*/intgetMaxWidth(Nodenode){intmaxWidth=0;intwidth;inth=height(node);inti;/* Get width of each level and compare the width with maximum width so far */for(i=1;i<=h;i++){width=getWidth(node,i);if(width>maxWidth)maxWidth=width;}returnmaxWidth;}/* Get width of a given level */intgetWidth(Nodenode,intlevel){if(node==null)return0;if(level==1)return1;elseif(level>1)returngetWidth(node.left,level-1)+getWidth(node.right,level-1);return0;}/* UTILITY FUNCTIONS *//* Compute the "height" of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node.*/intheight(Nodenode){if(node==null)return0;else{/* compute the height of each subtree */intlHeight=height(node.left);intrHeight=height(node.right);/* use the larger one */return(lHeight>rHeight)?(lHeight+1):(rHeight+1);}}/* Driver code */publicstaticvoidmain(Stringargs[]){BinaryTreetree=newBinaryTree();/* Constructed binary tree is: 1 / \ 2 3 / \ \ 4 5 8 / \ 6 7 */tree.root=newNode(1);tree.root.left=newNode(2);tree.root.right=newNode(3);tree.root.left.left=newNode(4);tree.root.left.right=newNode(5);tree.root.right.right=newNode(8);tree.root.right.right.left=newNode(6);tree.root.right.right.right=newNode(7);// Function callSystem.out.println(tree.getMaxWidth(tree.root));}}// This code has been contributed by Mayank Jaiswal
Python
# Python program to find the maximum width of# binary tree using Level Order Traversal.# A binary tree nodeclassNode:# Constructor to create a new nodedef__init__(self,data):self.data=dataself.left=Noneself.right=None# Function to get the maximum width of a binary treedefgetMaxWidth(root):maxWidth=0h=height(root)# Get width of each level and compare the# width with maximum width so farforiinrange(1,h+1):width=getWidth(root,i)if(width>maxWidth):maxWidth=widthreturnmaxWidth# Get width of a given leveldefgetWidth(root,level):ifrootisNone:return0iflevel==1:return1eliflevel>1:return(getWidth(root.left,level-1)+getWidth(root.right,level-1))# UTILITY FUNCTIONS# Compute the "height" of a tree -- the number of# nodes along the longest path from the root node# down to the farthest leaf node.defheight(node):ifnodeisNone:return0else:# compute the height of each subtreelHeight=height(node.left)rHeight=height(node.right)# use the larger onereturn(lHeight+1)if(lHeight>rHeight)else(rHeight+1)if__name__=="__main__":root=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(4)root.left.right=Node(5)root.right.right=Node(8)root.right.right.left=Node(6)root.right.right.right=Node(7)print(getMaxWidth(root))
C#
// C# program to calculate width of binary treeusingSystem;/* A binary tree node has data, pointer to left childand a pointer to right child */publicclassNode{publicintdata;publicNodeleft,right;publicNode(intitem){data=item;left=right=null;}}publicclassBinaryTree{publicNoderoot;/* Function to get the maximum width of a binary tree*/publicvirtualintgetMaxWidth(Nodenode){intmaxWidth=0;intwidth;inth=height(node);inti;/* Get width of each level and compare the width with maximum width so far */for(i=1;i<=h;i++){width=getWidth(node,i);if(width>maxWidth){maxWidth=width;}}returnmaxWidth;}/* Get width of a given level */publicvirtualintgetWidth(Nodenode,intlevel){if(node==null){return0;}if(level==1){return1;}elseif(level>1){returngetWidth(node.left,level-1)+getWidth(node.right,level-1);}return0;}/* UTILITY FUNCTIONS *//* Compute the "height" of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node.*/publicvirtualintheight(Nodenode){if(node==null){return0;}else{/* compute the height of each subtree */intlHeight=height(node.left);intrHeight=height(node.right);/* use the larger one */return(lHeight>rHeight)?(lHeight+1):(rHeight+1);}}/* Driver code */publicstaticvoidMain(string[]args){BinaryTreetree=newBinaryTree();/* Constructed binary tree is: 1 / \ 2 3 / \ \ 4 5 8 / \ 6 7 */tree.root=newNode(1);tree.root.left=newNode(2);tree.root.right=newNode(3);tree.root.left.left=newNode(4);tree.root.left.right=newNode(5);tree.root.right.right=newNode(8);tree.root.right.right.left=newNode(6);tree.root.right.right.right=newNode(7);// Function callConsole.WriteLine(""+tree.getMaxWidth(tree.root));}}
JavaScript
Output
3
Time Complexity: O(N2) in the worst case. Auxiliary Space: O(h) The only extra space used is the recursion stack, which in worst case is equal to the height of the tree O(h).
[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.
For each level, get the size of the queue (this gives the number of nodes at that level).
Update the answer with the maximum size encountered so far.
Push the children of each node into the queue and continue until the tree is fully traversed.
C++
// A queue based C++ program to find maximum width// of a Binary Tree#include<iostream>#include<queue>usingnamespacestd;/* A binary tree node has data, pointer to left child and a pointer to right child */structNode{intdata;structNode*left;structNode*right;Node(intd){this->data=d;this->left=this->right=NULL;}};// Function to find the maximum width of the tree// using level order traversalintmaxWidth(structNode*root){// Base caseif(root==NULL)return0;// Initialize resultintresult=0;// Do Level order traversal keeping track of number// of nodes at every level.queue<Node*>q;q.push(root);while(!q.empty()){// Get the size of queue when the level order// traversal for one level finishesintcount=q.size();// Update the maximum node count valueresult=max(count,result);// Iterate for all the nodes in the queue currentlywhile(count--){// Dequeue an node from queueNode*temp=q.front();q.pop();// Enqueue left and right children of// dequeued nodeif(temp->left!=NULL)q.push(temp->left);if(temp->right!=NULL)q.push(temp->right);}}returnresult;}// Driver codeintmain(){structNode*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(4);root->left->right=newNode(5);root->right->right=newNode(8);root->right->right->left=newNode(6);root->right->right->right=newNode(7);/* Constructed Binary tree is: 1 / \ 2 3 / \ \ 4 5 8 / \ 6 7 */cout<<maxWidth(root)<<endl;return0;}
Java
// Java program to calculate maximum width// of a binary tree using queueimportjava.util.LinkedList;importjava.util.Queue;publicclassmaxwidthusingqueue{/* A binary tree node has data, pointer to left child and a pointer to right child */staticclassnode{intdata;nodeleft,right;publicnode(intdata){this.data=data;}}// Function to find the maximum width of// the tree using level order traversalstaticintmaxwidth(noderoot){// Base caseif(root==null)return0;// Initialize resultintmaxwidth=0;// Do Level order traversal keeping// track of number of nodes at every levelQueue<node>q=newLinkedList<>();q.add(root);while(!q.isEmpty()){// Get the size of queue when the level order// traversal for one level finishesintcount=q.size();// Update the maximum node count valuemaxwidth=Math.max(maxwidth,count);// Iterate for all the nodes in// the queue currentlywhile(count-->0){// Dequeue an node from queuenodetemp=q.remove();// Enqueue left and right children// of dequeued nodeif(temp.left!=null){q.add(temp.left);}if(temp.right!=null){q.add(temp.right);}}}returnmaxwidth;}// Function callpublicstaticvoidmain(String[]args){noderoot=newnode(1);root.left=newnode(2);root.right=newnode(3);root.left.left=newnode(4);root.left.right=newnode(5);root.right.right=newnode(8);root.right.right.left=newnode(6);root.right.right.right=newnode(7);/* Constructed Binary tree is: 1 / \ 2 3 / \ \ 4 5 8 / \ 6 7 */System.out.println(maxwidth(root));}}
Python
# Python program to find the maximum width of binary# tree using Level Order Traversal with queue.from_collectionsimportdeque# A binary tree nodeclassNode:# Constructor to create a new nodedef__init__(self,data):self.data=dataself.left=Noneself.right=None# Function to get the maximum width of a binary treedefgetMaxWidth(root):# base caseifrootisNone:return0q=deque()maxWidth=0q.append(root)whileq:# Get the size of queue when the level order# traversal for one level finishescount=len(q)# Update the maximum node count valuemaxWidth=max(count,maxWidth)while(countisnot0):count=count-1temp=q.popleft()iftemp.leftisnotNone:q.append(temp.left)iftemp.rightisnotNone:q.append(temp.right)returnmaxWidthif__name__=="__main__":# Driver program to test above functionroot=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(4)root.left.right=Node(5)root.right.right=Node(8)root.right.right.left=Node(6)root.right.right.right=Node(7)""" Constructed binary tree is: 1 / \ 2 3 / \ \ 4 5 8 / \ 6 7 """print(getMaxWidth(root)))
C#
// C# program to calculate maximum width// of a binary tree using queueusingSystem;usingSystem.Collections.Generic;publicclassmaxwidthusingqueue{/* A binary tree node has data, pointer to left child and a pointer to right child */publicclassnode{publicintdata;publicnodeleft,right;publicnode(intdata){this.data=data;}}// Function to find the maximum width of// the tree using level order traversalstaticintmaxwidth(noderoot){// Base caseif(root==null)return0;// Initialize resultintmaxwidth=0;// Do Level order traversal keeping// track of number of nodes at every levelQueue<node>q=newQueue<node>();q.Enqueue(root);while(q.Count!=0){// Get the size of queue when the level order// traversal for one level finishesintcount=q.Count;// Update the maximum node count valuemaxwidth=Math.Max(maxwidth,count);// Iterate for all the nodes in// the queue currentlywhile(count-->0){// Dequeue an node from queuenodetemp=q.Dequeue();// Enqueue left and right children// of dequeued nodeif(temp.left!=null){q.Enqueue(temp.left);}if(temp.right!=null){q.Enqueue(temp.right);}}}returnmaxwidth;}publicstaticvoidMain(String[]args){noderoot=newnode(1);root.left=newnode(2);root.right=newnode(3);root.left.left=newnode(4);root.left.right=newnode(5);root.right.right=newnode(8);root.right.right.left=newnode(6);root.right.right.right=newnode(7);/* Constructed Binary tree is: 1 / \ 2 3 / \ \ 4 5 8 / \ 6 7 */Console.WriteLine(""+maxwidth(root));}}
JavaScript
// JavaScript program to calculate maximum width// of a binary tree using queueclassnode{constructor(data){this.left=null;this.right=null;this.data=data;}}// Function to find the maximum width of// the tree using level order traversalfunctionmaxwidth(root){// Base caseif(root==null)return0;// Initialize resultletmaxwidth=0;// Do Level order traversal keeping// track of number of nodes at every levelletq=[];q.push(root);while(q.length>0){// Get the size of queue when the level order// traversal for one level finishesletcount=q.length;// Update the maximum node count valuemaxwidth=Math.max(maxwidth,count);// Iterate for all the nodes in// the queue currentlywhile(count-->0){// Dequeue a node from queuelettemp=q.shift();// Enqueue left and right children// of dequeued nodeif(temp.left!=null){q.push(temp.left);}if(temp.right!=null){q.push(temp.right);}}}returnmaxwidth;}// Driver codeletroot=newnode(1);root.left=newnode(2);root.right=newnode(3);root.left.left=newnode(4);root.left.right=newnode(5);root.right.right=newnode(8);root.right.right.left=newnode(6);root.right.right.right=newnode(7);/* Constructed Binary tree is: 1 / \ 2 3 / \ \ 4 5 8 / \ 6 7 */console.log(maxwidth(root));
Output
3
[Expected Approach 2] Using Preorder Traversal - O(n) Time and O(n) Space
The idea behind this approach is to find the level of a node and increment the count of nodes for that level. The number of nodes present at a certain level is the width of that level.
Follow the steps mentioned below to implement the approach:
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;// Tree node structurestructNode{intdata;Node*left;Node*right;Node(intval){data=val;left=right=NULL;}};// Preorder traversal to count nodes at each levelvoidpreorder(Node*root,intlevel,vector<int>&count){if(root==NULL)return;// If this is the first node of this level, extend the vectorif(level==count.size()){count.push_back(0);}// Increase count of nodes at this levelcount[level]++;// Recurse for left and right subtreespreorder(root->left,level+1,count);preorder(root->right,level+1,count);}// Function to get maximum widthintgetMaxWidth(Node*root){vector<int>count;preorder(root,0,count);intmaxWidth=0;for(intc:count){maxWidth=max(maxWidth,c);}returnmaxWidth;}intmain(){Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(4);root->left->right=newNode(5);root->right->right=newNode(8);root->right->right->left=newNode(6);root->right->right->right=newNode(7);/* Constructed Binary tree is: 1 / \ 2 3 / \ \ 4 5 8 / \ 6 7 */cout<<getMaxWidth(root)<<endl;return0;}
C
#include<stdio.h>#include<stdlib.h>// Tree node structurestructNode{intdata;structNode*left;structNode*right;};// Create a new nodestructNode*newNode(intval){structNode*node=(structNode*)malloc(sizeof(structNode));node->data=val;node->left=node->right=NULL;returnnode;}// Preorder traversal to count nodes at each levelvoidpreorder(structNode*root,intlevel,intcount[],int*maxLevel){if(root==NULL)return;// If this is the first node of this level, extend countif(level>*maxLevel){*maxLevel=level;}// Increase count of nodes at this levelcount[level]++;// Recurse for left and right subtreespreorder(root->left,level+1,count,maxLevel);preorder(root->right,level+1,count,maxLevel);}// Function to get maximum widthintgetMaxWidth(structNode*root){intcount[1000]={0};// assume tree won't have more than 1000 levelsintmaxLevel=-1;preorder(root,0,count,&maxLevel);intmaxWidth=0;for(inti=0;i<=maxLevel;i++){if(count[i]>maxWidth)maxWidth=count[i];}returnmaxWidth;}intmain(){structNode*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(4);root->left->right=newNode(5);root->right->right=newNode(8);root->right->right->left=newNode(6);root->right->right->right=newNode(7);printf("%d\n",getMaxWidth(root));return0;}
Java
importjava.util.*;classNode{intdata;Nodeleft,right;Node(intval){data=val;left=right=null;}}publicclassMain{// Preorder traversal to count nodes at each levelstaticvoidpreorder(Noderoot,intlevel,List<Integer>count){if(root==null)return;// If this is the first node of this level, extend the listif(level==count.size()){count.add(0);}// Increase count of nodes at this levelcount.set(level,count.get(level)+1);// Recurse for left and right subtreespreorder(root.left,level+1,count);preorder(root.right,level+1,count);}// Function to get maximum widthstaticintgetMaxWidth(Noderoot){List<Integer>count=newArrayList<>();preorder(root,0,count);intmaxWidth=0;for(intc:count){maxWidth=Math.max(maxWidth,c);}returnmaxWidth;}publicstaticvoidmain(String[]args){Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.right=newNode(8);root.right.right.left=newNode(6);root.right.right.right=newNode(7);System.out.println(getMaxWidth(root));}}
Python
# Tree node structureclassNode:def__init__(self,val):self.data=valself.left=Noneself.right=None# Preorder traversal to count nodes at each leveldefpreorder(root,level,count):ifrootisNone:return# If this is the first node of this level, extend the listiflevel==len(count):count.append(0)# Increase count of nodes at this levelcount[level]+=1# Recurse for left and right subtreespreorder(root.left,level+1,count)preorder(root.right,level+1,count)# Function to get maximum widthdefgetMaxWidth(root):count=[]preorder(root,0,count)returnmax(count)ifcountelse0if__name__=="__main__":root=Node(1)root.left=Node(2)root.right=Node(3)root.left.left=Node(4)root.left.right=Node(5)root.right.right=Node(8)root.right.right.left=Node(6)root.right.right.right=Node(7)print(getMaxWidth(root))
C#
usingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intval){data=val;left=right=null;}}classProgram{// Preorder traversal to count nodes at each levelstaticvoidPreorder(Noderoot,intlevel,List<int>count){if(root==null)return;// If this is the first node of this level, extend the listif(level==count.Count){count.Add(0);}// Increase count of nodes at this levelcount[level]++;// Recurse for left and right subtreesPreorder(root.left,level+1,count);Preorder(root.right,level+1,count);}// Function to get maximum widthstaticintGetMaxWidth(Noderoot){List<int>count=newList<int>();Preorder(root,0,count);intmaxWidth=0;foreach(intcincount){maxWidth=Math.Max(maxWidth,c);}returnmaxWidth;}staticvoidMain(){Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.right=newNode(8);root.right.right.left=newNode(6);root.right.right.right=newNode(7);Console.WriteLine(GetMaxWidth(root));}}
JavaScript
// Tree node structureclassNode{constructor(data){this.data=data;this.left=null;this.right=null;}}// Preorder traversal to count nodes at each levelfunctionpreorder(root,level,count){if(root===null)return;// If this is the first node of this level, extend the arrayif(level===count.length){count.push(0);}// Increase count of nodes at this levelcount[level]++;// Recurse for left and right subtreespreorder(root.left,level+1,count);preorder(root.right,level+1,count);}// Function to get maximum widthfunctiongetMaxWidth(root){letcount=[];preorder(root,0,count);letmaxWidth=0;for(letcofcount){maxWidth=Math.max(maxWidth,c);}returnmaxWidth;}// Driver codeletroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.left.left=newNode(4);root.left.right=newNode(5);root.right.right=newNode(8);root.right.right.left=newNode(6);root.right.right.right=newNode(7);console.log(getMaxWidth(root));