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.
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.
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.
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.