VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-width-of-a-binary-tree/

⇱ Maximum width of a Binary Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum width of a Binary Tree

Last Updated : 26 Mar, 2026

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:

👁 widthtree

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.

[Naive Approach] By Counting Nodes at Each Level

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.

Steps to solve the problem:

  • Compute the height of the tree using recursion.
  • For each level from 1 to height:
  • Call a helper function that counts nodes at that level.
  • Update the maximum width after checking each level.

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.

Steps to solve the problem:

  • Use a queue to perform level order traversal.
  • 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.

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. 

Output
3
Comment