Given a Binary Tree consisting of N nodes, the task is to find the maximum width of the given tree where the maximum width is defined as the maximum of all the widths at each level of the given Tree.
The width of a tree for any level is defined as the number of nodes between the two extreme nodes of that level including the NULL node in between.
Examples:
Input:
          1
         /  \
        2   3
       / \    \
     4  5    8
    / \
   6  7
Output: 4
Explanation:
The width of level 1 is 1
The width of level 2 is 2
The width of level 3 is 4 (because it has a null node in between 5 and 8)
The width of level 4 is 2Therefore, the maximum width of the tree is the maximum of all the widths i.e., max{1, 2, 4, 2} = 4.
Input:
          1
         / Â
        2Â
       /
      3  Â
Output: 1
Approach: The given problem can be solved by representing the Binary Tree as the array representation of the Heap. Assume the index of a node is i then the indices of their children are (2*i + 1) and (2*i + 2). Now, for each level, find the position of the leftmost node and rightmost node in each level, then the difference between them will give the width of that level. Follow the steps below to solve this problem:
- Initialize two HashMap, say HMMax and HMMin that stores the position of the leftmost node and rightmost node in each level
- Create a recursive function getMaxWidthHelper(root, lvl, i) that takes the root of the tree, starting level of the tree initially 0, and position of the root node of the tree initially 0 and perform the following steps:
- If the root of the tree is NULL, then return.
- Store the leftmost node index at level lvl in the HMMin.
- Store the rightmost node index at level lvl in the HMMax.
- Recursively call for the left sub-tree by updating the value of lvl to lvl + 1 and i to (2*i + 1).
- Recursively call for the right sub-tree by updating the value of lvl to lvl + 1 and i to (2*i + 2).
- Call the function getMaxWidthHelper(root, 0, 0) to fill the HashMap.
- After completing the above steps, print the maximum value of (HMMax(L) – HMMin(L) + 1) among all possible values of level L.
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;Â
// Tree Node structurestruct Node{    int data;    Node *left, *right;         // Constructor    Node(int item)    {        data = item;        left = right = NULL;    }};Â
Node *root;int maxx = 0;Â
// Stores the position of leftmost// and rightmost node in each levelmap<int, int> hm_min;map<int, int> hm_max;Â
// Function to store the min and the// max index of each nodes in hashmapsvoid getMaxWidthHelper(Node *node,                       int lvl, int i){         // Base Case    if (node == NULL)     {        return;    }Â
    // Stores rightmost node index    // in the hm_max    if (hm_max[lvl])    {        hm_max[lvl] = max(i, hm_max[lvl]);    }    else    {        hm_max[lvl] = i;    }Â
    // Stores leftmost node index    // in the hm_min    if (hm_min[lvl])    {        hm_min[lvl] = min(i, hm_min[lvl]);    }Â
    // Otherwise    else    {        hm_min[lvl] = i;    }Â
    // If the left child of the node    // is not empty, traverse next    // level with index = 2*i + 1    getMaxWidthHelper(node->left, lvl + 1,                                 2 * i + 1);Â
    // If the right child of the node    // is not empty, traverse next    // level with index = 2*i + 2    getMaxWidthHelper(node->right, lvl + 1,                                  2 * i + 2);}Â
// Function to find the maximum// width of the treeint getMaxWidth(Node *root){         // Helper function to fill    // the hashmaps    getMaxWidthHelper(root, 0, 0);Â
    // Traverse to each level and    // find the maximum width    for(auto lvl : hm_max)     {        maxx = max(maxx, hm_max[lvl.first] -                          hm_min[lvl.first] + 1);    }Â
    // Return the result    return maxx;}Â
// Driver Codeint main(){Â Â Â Â Â Â Â Â Â /*Â Â Â Â Constructed binary tree is:Â Â Â Â Â Â Â Â Â Â 1Â Â Â Â Â Â Â Â /Â \Â Â Â Â Â Â Â 2Â Â Â 3Â Â Â Â Â /Â \Â Â Â \Â Â Â Â 4Â Â 5Â Â Â Â 8Â Â Â Â Â Â Â Â Â Â Â Â Â /Â \Â Â Â Â Â Â Â Â Â Â Â Â 6Â Â 7Â Â Â Â Â */Â Â Â Â root = new Node(1);Â Â Â Â root->left = new Node(2);Â Â Â Â root->right = new Node(3);Â Â Â Â root->left->left = new Node(4);Â Â Â Â root->left->right = new Node(5);Â Â Â Â root->right->right = new Node(8);Â Â Â Â root->right->right->left = new Node(6);Â Â Â Â root->right->right->right = new Node(7);Â
    // Function Call    cout << (getMaxWidth(root));}Â
// This code is contributed by mohit kumar 29 |
Java
// Java program for the above approachÂ
import java.util.*;Â
// Tree Node structureclass Node {Â Â Â Â int data;Â Â Â Â Node left, right;Â
    // Constructor    Node(int item)    {        data = item;        left = right = null;    }}Â
// Driver Codepublic class Main {Â
    Node root;    int maxx = 0;Â
    // Stores the position of leftmost    // and rightmost node in each level    HashMap<Integer, Integer> hm_min        = new HashMap<>();    HashMap<Integer, Integer> hm_max        = new HashMap<>();Â
    // Function to store the min and the    // max index of each nodes in hashmaps    void getMaxWidthHelper(Node node,                           int lvl, int i)    {        // Base Case        if (node == null) {            return;        }Â
        // Stores rightmost node index        // in the hm_max        if (hm_max.containsKey(lvl)) {            hm_max.put(lvl,                       Math.max(                           i, hm_max.get(lvl)));        }        else {            hm_max.put(lvl, i);        }Â
        // Stores leftmost node index        // in the hm_min        if (hm_min.containsKey(lvl)) {            hm_min.put(lvl,                       Math.min(                           i, hm_min.get(lvl)));        }Â
        // Otherwise        else {            hm_min.put(lvl, i);        }Â
        // If the left child of the node        // is not empty, traverse next        // level with index = 2*i + 1        getMaxWidthHelper(node.left, lvl + 1,                          2 * i + 1);Â
        // If the right child of the node        // is not empty, traverse next        // level with index = 2*i + 2        getMaxWidthHelper(node.right, lvl + 1,                          2 * i + 2);    }Â
    // Function to find the maximum    // width of the tree    int getMaxWidth(Node root)    {        // Helper function to fill        // the hashmaps        getMaxWidthHelper(root, 0, 0);Â
        // Traverse to each level and        // find the maximum width        for (Integer lvl : hm_max.keySet()) {            maxx                = Math.max(                    maxx,                    hm_max.get(lvl)                        - hm_min.get(lvl) + 1);        }Â
        // Return the result        return maxx;    }Â
    // Driver Code    public static void main(String args[])    {        Main tree = new Main();Â
        /*        Constructed binary tree is:              1            / \           2   3         / \   \        4  5    8                 / \                6  7         */        tree.root = new Node(1);        tree.root.left = new Node(2);        tree.root.right = new Node(3);        tree.root.left.left = new Node(4);        tree.root.left.right = new Node(5);        tree.root.right.right = new Node(8);        tree.root.right.right.left = new Node(6);        tree.root.right.right.right = new Node(7);Â
        // Function Call        System.out.println(            tree.getMaxWidth(                tree.root));    }} |
Python3
# Python3 program for the above approachÂ
# Tree Node structureclass Node:    def __init__(self, item):        self.data = item        self.left = None        self.right = NoneÂ
maxx = 0  # Stores the position of leftmost# and rightmost node in each levelhm_min = {}hm_max = {}  # Function to store the min and the# max index of each nodes in hashmapsdef getMaxWidthHelper(node, lvl, i):    # Base Case    if (node == None):        return    # Stores rightmost node index    # in the hm_max    if (lvl in hm_max):        hm_max[lvl] = max(i, hm_max[lvl])    else:        hm_max[lvl] = i      # Stores leftmost node index    # in the hm_min    if (lvl in hm_min):        hm_min[lvl] = min(i, hm_min[lvl])      # Otherwise    else:        hm_min[lvl] = i      # If the left child of the node    # is not empty, traverse next    # level with index = 2*i + 1    getMaxWidthHelper(node.left, lvl + 1, 2 * i + 1)      # If the right child of the node    # is not empty, traverse next    # level with index = 2*i + 2    getMaxWidthHelper(node.right, lvl + 1, 2 * i + 2)  # Function to find the maximum# width of the treedef getMaxWidth(root):    global maxx    # Helper function to fill    # the hashmaps    getMaxWidthHelper(root, 0, 0)      # Traverse to each level and    # find the maximum width    for lvl in hm_max.keys():        maxx = max(maxx, hm_max[lvl] - hm_min[lvl] + 1)      # Return the result    return maxx     """Constructed binary tree is:      1    / \   2   3 / \   \4  5    8         / \        6  7"""root = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(4)root.left.right = Node(5)root.right.right = Node(8)root.right.right.left = Node(6)root.right.right.right = Node(7)Â
# Function Callprint(getMaxWidth(root))Â
# This code is contributed by decode2207. |
C#
// C# program for the above approachusing System;using System.Collections.Generic;class GFG {         // A Binary Tree Node    class Node    {        public int data;        public Node left;        public Node right;              public Node(int item)        {            data = item;            left = right = null;        }    };         static int maxx = 0;      // Stores the position of leftmost    // and rightmost node in each level    static Dictionary<int, int> hm_min = new Dictionary<int, int>();     static Dictionary<int, int> hm_max = new Dictionary<int, int>();      // Function to store the min and the    // max index of each nodes in hashmaps    static void getMaxWidthHelper(Node node,                           int lvl, int i)    {        // Base Case        if (node == null) {            return;        }          // Stores rightmost node index        // in the hm_max        if (hm_max.ContainsKey(lvl)) {            hm_max[lvl] = Math.Max(i, hm_max[lvl]);        }        else {            hm_max[lvl] = i;        }          // Stores leftmost node index        // in the hm_min        if (hm_min.ContainsKey(lvl)) {            hm_min[lvl] = Math.Min(i, hm_min[lvl]);        }          // Otherwise        else {            hm_min[lvl] = i;        }          // If the left child of the node        // is not empty, traverse next        // level with index = 2*i + 1        getMaxWidthHelper(node.left, lvl + 1,                          2 * i + 1);          // If the right child of the node        // is not empty, traverse next        // level with index = 2*i + 2        getMaxWidthHelper(node.right, lvl + 1,                          2 * i + 2);    }      // Function to find the maximum    // width of the tree    static int getMaxWidth(Node root)    {        // Helper function to fill        // the hashmaps        getMaxWidthHelper(root, 0, 0);          // Traverse to each level and        // find the maximum width        foreach (KeyValuePair<int, int> lvl in hm_max) {            maxx = Math.Max(maxx, hm_max[lvl.Key] - hm_min[lvl.Key] + 1);        }          // Return the result        return maxx;    }     // Driver code  static void Main()   {      /*    Constructed binary tree is:          1        / \       2   3     / \   \    4  5    8             / \            6  7     */    Node root = new Node(1);    root.left = new Node(2);    root.right = new Node(3);    root.left.left = new Node(4);    root.left.right = new Node(5);    root.right.right = new Node(8);    root.right.right.left = new Node(6);    root.right.right.right = new Node(7);Â
    // Function Call    Console.Write(getMaxWidth(root));  }}Â
// This code is contributed by divyeshrabadiya07. |
Javascript
<script>Â
// JavaScript program for the above approachÂ
// Tree Node structureclass Node{Â Â Â Â constructor(item)Â Â Â Â {Â Â Â Â Â Â Â Â this.data=item;Â Â Â Â Â Â Â Â this.left=this.right=null;Â Â Â Â }}Â
// Driver Codelet root;let maxx = 0;Â
// Stores the position of leftmost    // and rightmost node in each levellet hm_min=new Map();let hm_max=new Map();Â
// Function to store the min and the    // max index of each nodes in hashmapsfunction getMaxWidthHelper(node,lvl,i){    // Base Case        if (node == null) {            return;        }          // Stores rightmost node index        // in the hm_max        if (hm_max.has(lvl)) {            hm_max.set(lvl,                       Math.max(                           i, hm_max.get(lvl)));        }        else {            hm_max.set(lvl, i);        }          // Stores leftmost node index        // in the hm_min        if (hm_min.has(lvl)) {            hm_min.set(lvl,                       Math.min(                           i, hm_min.get(lvl)));        }          // Otherwise        else {            hm_min.set(lvl, i);        }          // If the left child of the node        // is not empty, traverse next        // level with index = 2*i + 1        getMaxWidthHelper(node.left, lvl + 1,                          2 * i + 1);          // If the right child of the node        // is not empty, traverse next        // level with index = 2*i + 2        getMaxWidthHelper(node.right, lvl + 1,                          2 * i + 2);}Â
// Function to find the maximum    // width of the treefunction getMaxWidth(root){    // Helper function to fill        // the hashmaps        getMaxWidthHelper(root, 0, 0);          // Traverse to each level and        // find the maximum width        for (let [lvl, value] of hm_max.entries()) {            maxx                = Math.max(                    maxx,                    hm_max.get(lvl)                        - hm_min.get(lvl) + 1);        }          // Return the result        return maxx;}Â
// Driver Coderoot = new Node(1);root.left = new Node(2);root.right = new Node(3);root.left.left = new Node(4);root.left.right = new Node(5);root.right.right = new Node(8);root.right.right.left = new Node(6);root.right.right.right = new Node(7);Â
// Function Calldocument.write(getMaxWidth(root));Â
// This code is contributed by unknown2108Â
</script> |
4
Â
Time Complexity: O(N)
Auxiliary Space: O(N)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!
