Table of contents
1.
Introduction
2.
Maximum Width using Level-order Traversal
2.1.
Level Order Traversal without queue
2.2.
Level Order Traversal using Queue
2.3.
Algorithm
2.4.
Implementation in Java
2.5.
Java
2.5.1.
Output
2.5.2.
Complexity Analysis
2.6.
Implementation in python
2.7.
python
2.7.1.
Output
2.7.2.
Complexity Analysis
3.
Maximum Width Using Pre-order Traversal
3.1.
Algorithm
3.2.
Implementation in C++
3.3.
C++
3.3.1.
Output
3.3.2.
Complexity Analysis
4.
Maximum width Using a Special form of level Order Traversal
4.1.
C++
5.
Frequently Asked Questions
5.1.
What is the maximum width of a binary tree?
5.2.
What is the maximum number of nodes?
5.3.
How do you find the maximum width of a tree?
5.4.
How do you find the maximum element in a binary tree?
6.
Conclusion
Last Updated: Mar 27, 2024
Medium

Maximum Width of a Binary Tree

Author Alisha chhabra
2 upvotes
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Before diving into the problem, let’s first understand the width or breadth of a binary tree. The number of nodes present at the given level can determine the width of a binary tree. To be more specific, the maximum number of nodes at any binary tree level is the maximum width of a binary tree.

Maximum Width of a Binary Tree

The maximum width of a binary tree is the count of nodes without children. It represents the minimum nodes that must be traversed before needing to decide on the next node to visit.

Let’s understand it with some examples:

Example - 1:

maximum number of nodes

Since the maximum number of nodes present at Level-1 is 2, the maximum width of the binary tree is 2

Example-2:

maximum width of the binary tree

As you can see, the maximum number of nodes present at level 2 is 4; hence the maximum width of the binary tree is 4.

Now that you know how to find the maximum width of a binary tree, we need to build an algorithm that will allow us to return the maximum width for any binary tree.

It is recommended to Implement the stated maximum width in binary tree problem on your own before moving to the solution.

You can obtain a greater understanding of data structures and algorithms by solving on your own the stated maximum width problem in a binary tree. By addressing the problem on your own, you'll have the chance to experiment with different strategies, spot potential challenges, and improve your problem-solving abilities. 

Let's discuss the approach to solve the stated problem:

Maximum Width using Level-order Traversal

The naive yet effective approach can be using Level-wise traversal. As we aim to find the maximum number of nodes level-wise thus, employing Level order Traversal (or Breadth-first search) will suffice.

Level-order traversal or breadth-first search starts traversing at the tree from root and explores all nodes at the present level before moving on to the nodes at the next depth level.

Consider the below diagram:

Maximum Width using Level-order Traversal

This is how the Level order traversal works in trees or any data structure

Now let’s understand the algorithm for finding the maximum width of a binary tree using the Level-order traversal.

Level-order traversal

In the given binary tree:

Level 1 has 1 node, so maxWidth = 1

Level 2 has 2 node, so maxWidth = 2( 2 > 1)

Level 3 has 4 node, so maxWidth = 4( 4 > 2)

Hence, the maximum width will be 4.

Level Order Traversal without queue

Without using a queue, level order traversal in a binary tree involves tracking each level's nodes separately, usually through depth-first or recursion-based approaches. This method typically requires additional bookkeeping and may not be as efficient as using a queue. In this method:

  • You would typically use a recursive approach.
  • Start by calculating the height of the binary tree. Then, iterate from height 1 to the maximum height.
  • At each level, traverse the tree and print the nodes encountered at that level.
  • You might need a helper function that takes the root node and the current level as parameters.
  • This method involves multiple passes through the tree and might not be as efficient as using a queue.

Level Order Traversal using Queue

Level order traversal using a queue involves iterating through each level of a binary tree horizontally. Starting from the root node, each level's nodes are processed sequentially by enqueueing child nodes and dequeueing parent nodes. This method ensures nodes are visited in a breadth-first manner, making it efficient and easy to implement. In this method:

  • Initialize a queue and enqueue the root node.
  • Begin a loop that continues until the queue is empty.
  • Inside the loop, dequeue a node, process it (print its value, for example), and enqueue its children (if any) from left to right.
  • Repeat this process until all nodes are processed.
  • This method ensures that nodes are visited level by level, from left to right, which is the characteristic of level order traversal.
  • Using a queue helps in keeping track of the nodes to be processed at each level efficiently, ensuring a breadth-first search pattern.

Also read - Boundary Traversal of Binary Tree

Algorithm

  1. Define the Node class, which contains three attributes: data, left, and right where, the left child of the node is represented by left, and the right child of the node is represented by right
     
  2. When a node is constructed, data is passed to the node's data attribute, and both left and right are set to null
     
  3. Create a new class with the root attribute. The root represents the tree's root node and sets its value to null
     
  4. findMaxWidth() will find out the maximum width of a binary tree
  • The variable maxWidth will keep track of the total number of nodes in each level
     
  • The queue is used to traverse the binary tree on a level-by-level basis
     
  • The function also determines if the root is null, indicating that the tree is empty
     
  • If this is not the case, add the root node to the queue. Variable level_nodes keep track of the number of nodes in each level
     
  • Remove the node from the front of the queue and add its left and right children to the queue if the number of level_nodes > 0
node class
  • In the above diagram, node 1 will be eliminated in the first iteration, and its children nodes 2 and 3 will be added to the queue. Node will be eliminated in the second iteration, and its offspring 4 and 5 will be added to the queue, and so on
     
  • MaxWidth is a variable that stores the maximum width (maxWidth, level_nodes). As a result, it will always represent the maximum number of nodes at any given time
     

5. Finally, Print the maxWidth

Now, let’s look at the Implementation:

Implementation in Java

  • Java

Java

// Java Implementation to find the maximum width of a binary tree

import java.util.LinkedList; 
import java.util.Queue; 
 
public class BinaryTree { 
    
     // Represent the node of a binary tree

     public static class Node{ 
         /* Node has three components -> data , left and right
                   data
                    / \
               left right       
         */
       int data; 
       Node left; 
       Node right; 
       
       // Function for assigning the respected values to the components 
       public Node(int data){ 
          
         // Assign data to the new node and set its left and right children to null 
        
         this.data = data; 
         this.left = null; 
         this.right = null; 
       } 
     } 
      
     //Represent the root of a binary tree 
     public Node root; 
    
     // Constructor for initially assigning the root to null
     public BinaryTree(){ 
       root = null; 
     } 
      
     // findMaxWidth() will find out the maximum width of the given binary tree 
     public int findMaxWidth() { 
         int maxWidth = 0; 
          
         // Variable level_nodes keep note of number of nodes in each level 
         int level_nodes = 0; 
         // queue data structure will be used to keep note of the nodes of tree level-wise 
         Queue<Node> queue = new LinkedList<Node>(); 
          
         // Check if root is null, then width will be 0 
         if(root == null) { 
         // print Tree is empty and return
             System.out.println("Tree is empty"); 
             return 0; 
         } 
         else { 
             //Add the root node to queue as it serves the first level 
             queue.add(root); 
            
             // Loop until the queue becomes empty 
             while(queue.size() != 0) { 
                  
                 //Variable level_nodes will hold the size of queue i.e. number of elements in queue 
                 level_nodes = queue.size();
                
                 //maxWidth will hold the maximum width among the level_nodes and maxWidth itself.  
                 maxWidth = Math.max(maxWidth, level_nodes); 
                  
                 /*  If variable level_nodes contains more than one node then, for each node, its left and right child will be added to the queue  */
                
                 while(level_nodes > 0) { 
                    Node curr = queue.remove(); 
                    if(curr.left != null)  
                        queue.add(curr.left); 
                    if(curr.right != null)  
                        queue.add(curr.right); 
                   // decrement the level_nodes by one so that it jumps to the remaining size
                    level_nodes--; 
                 } 
             } 
         } 
         return maxWidth; 
     } 
      
     public static void main(String[] args) { 
          
         BinaryTree binaryT = new BinaryTree(); 
         /* Construct the following binary tree
                        1
                      / \
                     2 3
                    / \ / \
                   4 5 6  7
         */
         binaryT.root = new Node(1); 
         binaryT.root.left = new Node(2); 
         binaryT.root.right = new Node(3); 
         binaryT.root.left.left = new Node(4); 
         binaryT.root.left.right = new Node(5); 
         binaryT.root.right.left = new Node(6); 
         binaryT.root.right.right = new Node(7); 
          
         // print the maximum width of the given tree 
         System.out.println("Maximum width of a binary tree: " + binaryT.findMaxWidth()); 
     } 
You can also try this code with Online Java Compiler
Run Code

 

Output

Maximum width of a binary tree: 4

 

Complexity Analysis

Time Complexity: O(N), where N is the number of nodes present in a binary tree. Since each node is processed once, therefore the time complexity is O(N).

Space Complexity: The Space Complexity is O(W), where W is the maximum width of a binary tree. Because, In level order traversal, a queue is kept whose maximum size at any given time can be as large as the binary tree's maximum width. In the worst case, it can be O(N), where N is the number of nodes present in a binary tree.

Implementation in python

  • python

python

# Python Implementation to find the maximum width of a binary tree

# Represent a node of a binary tree 
class Node: 
   def __init__(self,data): 
       #  Assign data to the new node and set its left and right children to None 
       """  Node has three components -> data , left and right
                   data
                    / \
               left right
      """
       self.data = data; 
       self.left = None; 
       self.right = None; 
 
class BinaryTree: 
   def __init__(self): 
       # Represent the root of the binary tree 
       self.root = None; 
    
   # findMaxWidth() will find out the maximum width of a given binary tree 
   def findMaxWidth(self): 
       maxWidth = 0; 
       # Variable Level_nodes keep tracks of the number of nodes in each level 
       level_nodes = 0; 
       # queue data structure will be used to keep note of the nodes of tree level-wise 
       queue = []; 
        
       # Check if the root is null, then width will be 0 
       if(self.root == None): 
           print("Tree is empty"); 
           return 0;
       # If the root isn't empty
       else: 
           # Add the root node to queue as it serves the first level 
           queue.append(self.root); 
          
           # Loop until the queue becomes empty
           while(len(queue) != 0): 
                
               # Variable level_nodes will hold the size of queue i.e. number of elements in queue 
               level_nodes = len(queue); 
              
               # maxWidth will hold maximum width  
               maxWidth = max(maxWidth, level_nodes); 
                
               # If variable level_nodes contains more than one node  
               # then, for each node, its left and right child will be added to the queue 
               while(level_nodes > 0): 
                   curr = queue.pop(0); 
                   if(curr.left != None): 
                       queue.append(curr.left); 
                   if(curr.right != None): 
                       queue.append(curr.right); 
                   # decrement the level_nodes by one so that it jumps to the remaining size
                   level_nodes = level_nodes - 1; 
       return maxWidth; 

 
binaryT = BinaryTree(); 

#Add nodes to the binary tree
""" Construct the following binary tree
                         1
                      / \
                     2  3
                    / \  / \
                   4 5 6  7
"""      

binaryT.root = Node(1); 
binaryT.root.left = Node(2); 
binaryT.root.right = Node(3); 
binaryT.root.left.left = Node(4); 
binaryT.root.left.right = Node(5); 
binaryT.root.right.left = Node(6); 
binaryT.root.right.right = Node(7); 
 
# print the maximum width of given tree 
print("Maximum width of a binary tree: " + str(binaryT.findMaxWidth()));
You can also try this code with Online Python Compiler
Run Code

 

Output

Maximum width of a binary tree: 4

 

Complexity Analysis

Time Complexity: O(N), where N is the number of nodes present in a binary tree. Since each node is processed once, therefore the time taken will be O(N).

Space Complexity: O(W), where W is the maximum width of a binary tree. Because, In level order traversal, a queue is kept whose maximum size at any given time can be as large as the binary tree's maximum width. In the worst case, it can be O(N), where N is the number of nodes present in a binary tree.

Pictorial Representation of the above example in implementation:-

Binary Tree Queue
Queue node levels
Node maximum width

Maximum Width Using Pre-order Traversal

The approach is finding the maximum width of the binary tree using pre-order traversal. Pre-order traversal starts traversing at the tree from the root and explores all nodes of the left subtree before moving on to the nodes of the right subtree.
Consider the below diagram: 

Maximum Width Using Pre-order Traversal

Appling pre-order traversal, we will get the following order: 1 2 4 5 3 6 7

Now let’s understand the algorithm for finding the maximum width of a binary tree using the Pre-order traversal.

This method aims to determine a node's level and increase the number of nodes at that level. The number of nodes present there determines the width of a level.

pre-order traversal

Algorithm

  1. Define the Node class, which contains three attributes: data, left, and right, where the left child of the node is represented by left, and the right child of the node is represented by right
     
  2. When a node is constructed, data is passed to the node's data attribute, and both left and right are set to null
     
  3. Create a new array cnt[] with a size equal to the tree's height and initialize with Zero
     
  4. Preorder traverse the tree and update the cnt[] array's entries
     
  5. Find the maximum width by finding the level with the most nodes
     
  6. Return the level's value

Implementation in C++

  • C++

C++

#include <bits/stdc++.h>
using namespace std;

class node {
public:
   int data;
   node* left;
   node* right;
   node(int x)
   {
       this->data = x;
       this->left = this->right = NULL;
   }
};



int Treeheight(node* node);

int findMax(int arr[], int n);

void findMaxWidth(node* root, int cnt[], int level);


int Treeheight(node* node)
{
   if (node == NULL)
       return 0;
   else {
       /* find the height of each subtree */
       int lHeight = Treeheight(node->left);
       int rHeight = Treeheight(node->right);
    

       return (lHeight > rHeight) ? (lHeight + 1)
                                  : (rHeight + 1);
   }
}


// Return the maximum value from temporary(cnt) array
int findMax(int arr[], int n)
{
   int max = arr[0];
   int i;
   for (i = 0; i < n; i++) {
       if (arr[i] > max)
           max = arr[i];
   }
   return max;
}


int getMaxWidth(node* root)
{
   int width;
   int h = Treeheight(root);

   // Create an  temporary array
   int* cnt = new int[h];

   int level = 0;

   // Traversal using preorder traversal
   findMaxWidth(root, cnt, level);

   // Return the maximum value from temporary array
   return findMax(cnt, h);
}



void findMaxWidth(node* root,
                     int cnt[], int level)
{
   if (root) {
       cnt[level]++;
       findMaxWidth(root->left, cnt, level + 1);
       findMaxWidth(root->right, cnt, level + 1);
   }
}


/* Driver code*/
int main()
{
   node* root = new node(6);
   root->left = new node(3);
   root->right = new node(5);
   root->left->left = new node(2);
   root->left->right = new node(7);
   root->right->right = new node(8);
   root->right->right->left = new node(1);
   root->right->right->right = new node(2);

   cout << "The maximum width of the given tree is " << getMaxWidth(root)
        << endl;
   return 0;
}
You can also try this code with Online C++ Compiler
Run Code


Output

The maximum width of the given tree is 3

 

Complexity Analysis

Time Complexity: We are traversing the tree in preorder, so the time complexity is O(N).

Space Complexity: The space complexity of the given solution is O(h) since we are using a temporary array of size h. Here, h is the height of the given binary tree.

Maximum width Using a Special form of level Order Traversal

To find the maximum width of a binary tree using a special form of level order traversal, you can employ a modified breadth-first search (BFS) approach. Here's how you can do it:

  1. Initialize: Initialize a queue and enqueue the root node along with its position, which can be represented as an index.
  2. Traverse Level by Level: While the queue is not empty, dequeue each node and keep track of its position.
  3. Update Maximum Width: At each level, calculate the width by subtracting the position of the leftmost node from the position of the rightmost node.
  4. Enqueue Children with Updated Positions: Enqueue the children of the dequeued node along with updated positions. For the left child, position * 2 and for the right child, position * 2 + 1.
  5. Update Maximum Width: Update the maximum width if the current level's width is greater than the previous maximum width.
  6. Repeat: Repeat the process until all levels are traversed.

Here's a C++ example to illustrate the process:

  • C++

C++

#include <iostream>
#include <queue>
using namespace std;

// Structure of a binary tree node
struct TreeNode {
int data;
TreeNode* left;
TreeNode* right;
TreeNode(int val) : data(val), left(nullptr), right(nullptr) {}
};

// Function to find the maximum width of a binary tree
int maxWidth(TreeNode* root) {
if (root == nullptr) return 0;

int maxWidth = 0;
queue<TreeNode*> q;
q.push(root);

while (!q.empty()) {
// Number of nodes at the current level
int count = q.size();

maxWidth = max(maxWidth, count);

// Enqueue children of all nodes at current level
while (count--) {
TreeNode* temp = q.front();
q.pop();

// Enqueue left child
if (temp->left != nullptr) q.push(temp->left);

// Enqueue right child
if (temp->right != nullptr) q.push(temp->right);
}
}
return maxWidth;
}

int main() {
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
root->right->right = new TreeNode(8);
root->right->right->left = new TreeNode(6);
root->right->right->right = new TreeNode(7);

cout << "Maximum width of the binary tree is: " << maxWidth(root) << endl;

return 0;
}
You can also try this code with Online C++ Compiler
Run Code

Output:

Maximum width of the binary tree is: 3

 

This code demonstrates finding the maximum width of a binary tree using a queue-based level order traversal. We keep track of the number of nodes at each level and update the maximum width accordingly. Finally, we return the maximum width of the binary tree.

 

Also read about - Difference Between Any Two Levels of Binary Tree

Frequently Asked Questions

What is the maximum width of a binary tree?

The number of nodes at each level determines the width of the binary tree. As a result, the level with the most nodes will define the binary tree's maximum width.

What is the maximum number of nodes?

If a binary tree has h levels, the maximum number of nodes is when all levels are filled. 

The total number of nodes is 2^0 + 2^1 +.... 2^h = 2^(h+1)-1.

How do you find the maximum width of a tree?

Level-order traversal or Pre-order traversal starts traversing at the tree from the root and explores all nodes at the present level before moving on to the nodes at the next depth level. By calculating nodes at each level, we will find the maximum width with the level having the maximum no of nodes.

How do you find the maximum element in a binary tree?

In Binary Search Tree, we can find the maximum by traversing right pointers until we reach the rightmost node. But in Binary Tree, we must visit every node to figure out maximum. So the idea is to traverse the given tree and for every node return a maximum of 3 values. Node's data.

Conclusion

To summarise the session, we looked at finding the maximum width of a binary tree, which reflects the maximum number of nodes at any level. We've also looked at the intricacy of the proposed technique. 

Don't sit idle; keep practicing the most frequently asked questions to improve your learning and ensure a successful future.

Recommended Reading: 

Do check out The Interview guide for Product Based Companies as well as Practice Interview Problems of top tech companies.

Also check out some of the Guided Paths on topics such as Operating Systems, Computer Networks, DBMS, System Design, etc. as well as some Contests, Test Series, Interview Bundles, and some Interview Experiences curated by top Industry Experts only on Coding Ninjas Studio.

Happy Learning Ninja!

Live masterclass