Related Articles
Maximum width of an N-ary tree
• Last Updated : 21 Jan, 2021

Given an N-ary tree, the task is to find the maximum width of the given tree. The maximum width of a tree is the maximum of width among all levels.

Examples:

Input:

```                   4
/ | \
2  3 -5
/ \    /\
-1   3 -2  6```

Output:
Explanation:
Width of 0th level is 1.
Width of 1st level is 3.
Width of 2nd level is 4.
Therefore, the maximum width is 4

Input:

```              1
/ | \
2  -1  3
/  \      \
4    5      8
/           / | \
2           6  12  7  ```

Output:

Approach: This problem can be solved using BFS. The idea is to perform level order traversal of the tree. While doing traversal, process nodes of different levels separately. For every level being processed, count the number of nodes present at each level and keep track of the maximum count. Follow the steps below to solve the problem:

1. Initialize a variable, say maxWidth to store the required maximum width of the tree.
2. Initialize a Queue to perform the level order traversal of the given tree.
3. Push the root node into the queue.
4. If size of the queue exceeds maxWidth for any level, then update maxWidth to the size of the queue.
5. Traverse the queue and push all the nodes of the next level into the queue and pop all the nodes of the current level.
6. Repeat the above steps until all the levels of the tree are traversed.
7. Finally, return the final value of maxWidth.

Below is the implementation of the above approach:

## C++

 `// C++ program to implement``// the above approach` `#include ``using` `namespace` `std;` `// Function to find the maximum width of``// the tree using level order traversal``int` `maxWidth(``int` `N, ``int` `M,``             ``vector<``int``> cost,``             ``vector > s)``{``    ``// Store the edges of the tree``    ``vector<``int``> adj[N];``    ``for` `(``int` `i = 0; i < M; i++) {``        ``adj[s[i][0]].push_back(``            ``s[i][1]);``    ``}` `    ``// Stores maximum width``    ``// of the tree``    ``int` `result = 0;` `    ``// Stores the nodes``    ``// of each level``    ``queue<``int``> q;` `    ``// Insert root node``    ``q.push(0);` `    ``// Perform level order``    ``// traversal on the tree``    ``while` `(!q.empty()) {` `        ``// Stores the size of``        ``// the queue``        ``int` `count = q.size();` `        ``// Update maximum width``        ``result = max(count, result);` `        ``// Push the nodes of the next``        ``// level and pop the elements``        ``// of the current level``        ``while` `(count--) {` `            ``// Get element from the``            ``// front the Queue``            ``int` `temp = q.front();``            ``q.pop();` `            ``// Push all nodes of the next level.``            ``for` `(``int` `i = 0; i < adj[temp].size();``                 ``i++) {``                ``q.push(adj[temp][i]);``            ``}``        ``}``    ``}` `    ``// Return the result.``    ``return` `result;``}` `// Driver Code``int` `main()``{``    ``int` `N = 11, M = 10;` `    ``vector > edges;``    ``edges.push_back({ 0, 1 });``    ``edges.push_back({ 0, 2 });``    ``edges.push_back({ 0, 3 });``    ``edges.push_back({ 1, 4 });``    ``edges.push_back({ 1, 5 });``    ``edges.push_back({ 3, 6 });``    ``edges.push_back({ 4, 7 });``    ``edges.push_back({ 6, 10 });``    ``edges.push_back({ 6, 8 });``    ``edges.push_back({ 6, 9 });` `    ``vector<``int``> cost``        ``= { 1, 2, -1, 3, 4, 5,``            ``8, 2, 6, 12, 7 };` `    ``/* Constructed tree is:``                ``1``              ``/ | \``            ``2  -1  3``          ``/  \      \``         ``4    5      8``        ``/          / | \``       ``2          6  12  7``    ``*/` `    ``cout << maxWidth(N, M, cost, edges);` `    ``return` `0;``}`

## Java

 `// Java program to implement``// the above approach``import` `java.io.*;``import` `java.util.*;``class` `GFG``{``  ` `    ``// Function to find the maximum width of``    ``// the tree using level order traversal``    ``static` `int` `maxWidth(``int` `N, ``int` `M,ArrayList cost,``                        ``ArrayList > s)``    ``{``      ` `        ``// Store the edges of the tree``        ``ArrayList > adj =``          ``new` `ArrayList >();``        ``for``(``int` `i = ``0``; i < N; i++)``        ``{``            ``adj.add(``new` `ArrayList());``        ``}``        ``for``(``int` `i = ``0``; i < M; i++)``        ``{``            ``adj.get(s.get(i).get(``0``)).add(s.get(i).get(``1``));``        ``}``      ` `        ``// Stores maximum width``        ``// of the tree``        ``int` `result = ``0``;``      ` `        ``// Stores the nodes``        ``// of each level``        ``Queue q = ``new` `LinkedList<>();``      ` `        ``// Insert root node``        ``q.add(``0``);``      ` `        ``// Perform level order``        ``// traversal on the tree``        ``while``(q.size() != ``0``)``        ``{``          ` `            ``// Stores the size of``            ``// the queue``            ``int` `count = q.size();``          ` `            ``// Update maximum width``            ``result = Math.max(count, result);``          ` `            ``// Push the nodes of the next``            ``// level and pop the elements``            ``// of the current level``            ``while``(count-->``0``)``            ``{``              ` `                ``// Get element from the``                ``// front the Queue``                 ``int` `temp = q.remove();``              ` `                ``// Push all nodes of the next level.``                 ``for``(``int` `i = ``0``; i < adj.get(temp).size(); i++)``                 ``{``                     ``q.add(adj.get(temp).get(i));``                 ``}``            ``}``        ``}``      ` `        ``// Return the result.``        ``return` `result;``    ``}``  ` `    ``// Driver Code``    ``public` `static` `void` `main (String[] args)``    ``{``        ``int` `N = ``11``, M = ``10``;``        ``ArrayList > edges = ``new` `ArrayList >();``        ``edges.add(``new` `ArrayList(Arrays.asList( ``0``, ``1``)));``        ``edges.add(``new` `ArrayList(Arrays.asList( ``0``, ``2``)));``        ``edges.add(``new` `ArrayList(Arrays.asList( ``0``, ``3``)));``        ``edges.add(``new` `ArrayList(Arrays.asList(``1``,``4``)));``        ``edges.add(``new` `ArrayList(Arrays.asList(``1``,``5``)));``        ``edges.add(``new` `ArrayList(Arrays.asList(``3``,``6``)));``        ``edges.add(``new` `ArrayList(Arrays.asList(``4``,``7``)));``        ``edges.add(``new` `ArrayList(Arrays.asList(``6``,``10``)));``        ``edges.add(``new` `ArrayList(Arrays.asList(``6``,``8``)));``        ``edges.add(``new` `ArrayList(Arrays.asList(``6``,``9``)));` `        ``ArrayList cost = ``new` `ArrayList(Arrays.asList(``1``, ``2``, -``1``, ``3``, ``4``, ``5``,``8``, ``2``, ``6``, ``12``, ``7` `));       ``        ``/* Constructed tree is:``                ``1``              ``/ | \``            ``2  -1  3``          ``/  \      \``         ``4    5      8``        ``/          / | \``       ``2          6  12  7``    ``*/``        ``System.out.println(maxWidth(N, M, cost, edges));``    ``}``}` `// This code is contributed by avanitrachhadiya2155`

## Python3

 `# Python3 program to implement``# the above approach``from` `collections ``import` `deque` `# Function to find the maximum width of``#. he tree using level order traversal``def` `maxWidth(N, M, cost, s):``    ` `    ``# Store the edges of the tree``    ``adj ``=` `[[] ``for` `i ``in` `range``(N)]``    ``for` `i ``in` `range``(M):``        ``adj[s[i][``0``]].append(s[i][``1``])` `    ``# Stores maximum width``    ``# of the tree``    ``result ``=` `0` `    ``# Stores the nodes``    ``# of each level``    ``q ``=` `deque()` `    ``# Insert root node``    ``q.append(``0``)` `    ``# Perform level order``    ``# traversal on the tree``    ``while` `(``len``(q) > ``0``):` `        ``# Stores the size of``        ``# the queue``        ``count ``=` `len``(q)` `        ``# Update maximum width``        ``result ``=` `max``(count, result)` `        ``# Push the nodes of the next``        ``# level and pop the elements``        ``# of the current level``        ``while` `(count > ``0``):` `            ``# Get element from the``            ``# front the Queue``            ``temp ``=` `q.popleft()` `            ``# Push all nodes of the next level.``            ``for` `i ``in` `adj[temp]:``                ``q.append(i)``                ` `            ``count ``-``=` `1` `    ``# Return the result.``    ``return` `result` `# Driver Code``if` `__name__ ``=``=` `'__main__'``:``    ` `    ``N ``=` `11``    ``M ``=` `10` `    ``edges ``=` `[]``    ``edges.append([``0``, ``1``])``    ``edges.append([``0``, ``2``])``    ``edges.append([``0``, ``3``])``    ``edges.append([``1``, ``4``])``    ``edges.append([``1``, ``5``])``    ``edges.append([``3``, ``6``])``    ``edges.append([``4``, ``7``])``    ``edges.append([``6``, ``1``])``    ``edges.append([``6``, ``8``])``    ``edges.append([``6``, ``9``])` `    ``cost ``=` `[ ``1``, ``2``, ``-``1``, ``3``, ``4``, ``5``,``             ``8``, ``2``, ``6``, ``12``, ``7``]``    ` `    ``# Constructed tree is:``    ``#           1``    ``#         / | \``    ``#        2 -1  3``    ``#       / \       \``    ``#      4   5        8``    ``#     /          / | \``    ``#  2         6  12  7``    ``print``(maxWidth(N, M, cost, edges))` `# This code is contributed by mohit kumar 29`

## C#

 `// C# program to implement``// the above approach``using` `System;``using` `System.Collections.Generic;` `class` `GFG{``    ` `// Function to find the maximum width of``// the tree using level order traversal``static` `int` `maxWidth(``int` `N, ``int` `M, List<``int``> cost,``                             ``List> s)``{``    ` `    ``// Store the edges of the tree``    ``List> adj = ``new` `List>();``    ``for``(``int` `i = 0; i < N; i++)``    ``{``        ``adj.Add(``new` `List<``int``>());``    ``}``    ` `    ``for``(``int` `i = 0; i < M; i++)``    ``{``        ``adj[s[i][0]].Add(s[i][1]);``    ``}``    ` `    ``// Stores maximum width``    ``// of the tree``    ``int` `result = 0;``    ` `    ``// Stores the nodes``    ``// of each level``    ``Queue<``int``> q = ``new` `Queue<``int``>();``    ` `    ``// Insert root node``    ``q.Enqueue(0);``    ` `    ``// Perform level order``    ``// traversal on the tree``    ``while` `(q.Count != 0)``    ``{``        ` `        ``// Stores the size of``        ``// the queue``        ``int` `count = q.Count;``        ` `        ``// Update maximum width``        ``result = Math.Max(count, result);``        ` `        ``// Push the nodes of the next``        ``// level and pop the elements``        ``// of the current level``        ``while` `(count-- > 0)``        ``{``            ` `            ``// Get element from the``            ``// front the Queue``            ``int` `temp = q.Dequeue();``            ` `            ``// Push all nodes of the next level.``            ``for``(``int` `i = 0; i < adj[temp].Count; i++)``            ``{``                ``q.Enqueue(adj[temp][i]);``            ``}``        ``}``    ``}``    ` `    ``// Return the result.``    ``return` `result;``}` `// Driver Code``static` `public` `void` `Main()``{``    ``int` `N = 11, M = 10;``    ` `    ``List> edges = ``new` `List>();``    ``edges.Add(``new` `List<``int``>(){0, 1});``    ``edges.Add(``new` `List<``int``>(){0, 2});``    ``edges.Add(``new` `List<``int``>(){0, 3});``    ``edges.Add(``new` `List<``int``>(){1, 4});``    ``edges.Add(``new` `List<``int``>(){1, 5});``    ``edges.Add(``new` `List<``int``>(){3, 6});``    ``edges.Add(``new` `List<``int``>(){4, 7});``    ``edges.Add(``new` `List<``int``>(){6, 10});``    ``edges.Add(``new` `List<``int``>(){6, 8});``    ``edges.Add(``new` `List<``int``>(){6, 9});``    ` `    ``List<``int``> cost = ``new` `List<``int``>(){ 1, 2, -1, 3,``                                      ``4, 5, 8, 2,``                                      ``6, 12, 7 };``    ``/* Constructed tree is:``            ``1``          ``/ | \``        ``2  -1  3``      ``/  \      \``     ``4    5      8``    ``/          / | \``   ``2          6  12  7``    ``*/``    ` `    ``Console.WriteLine(maxWidth(N, M, cost, edges));``}``}` `// This code is contributed by rag2127`
Output:
`4`

Time Complexity: O(N)
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up