Given a binary tree, write an efficient algorithm to compute the maximum number of nodes in any level in the binary tree.

For example, the maximum number of nodes in any level in the binary tree below is 4.

 
Maximum width of Binary Tree

Practice this problem

1. Iterative Approach

In an iterative version, perform a level order traversal on the tree. We can easily modify level order traversal to maintain the maximum number of nodes at the current level. Then the result is equal to the maximum number of nodes at any level in the tree.

This is demonstrated below in C++, Java, and Python:

C++


Download  Run Code

Output:

The maximum width is 4

Java


Download  Run Code

Output:

The maximum width is 4

Python


Download  Run Code

Output:

The maximum width is 4

The time complexity of the above solution is O(n), where n is the total number of nodes in the binary tree. The auxiliary space required by the program is O(n) for the queue.

2. Recursive Approach

We can also solve this problem recursively by using hashing. We traverse the tree in a preorder fashion and store the count of nodes present in each level in a map. Finally, traverse the map and return the maximum value found.

Please note that we can also traverse the tree in an inorder or postorder fashion. The implementation can be seen below in C++, Java, and Python:

C++


Download  Run Code

Output:

The maximum width is 4

Java


Download  Run Code

Output:

The maximum width is 4

Python


Download  Run Code

Output:

The maximum width is 4

The time complexity of the above solution is O(n) and requires O(n) extra space, where n is the size of the binary tree.