Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Maximum width of a Binary Tree with null value

  • Last Updated : 14 Sep, 2021

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.

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.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

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 2

Therefore, 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 structure
struct 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 level
map<int, int> hm_min;
map<int, int> hm_max;
 
// 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[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 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(auto lvl : hm_max)
    {
        maxx = max(maxx, hm_max[lvl.second] -
                         hm_min[lvl.second] + 1);
    }
 
    // Return the result
    return maxx;
}
 
// Driver Code
int 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 structure
class Node {
    int data;
    Node left, right;
 
    // Constructor
    Node(int item)
    {
        data = item;
        left = right = null;
    }
}
 
// Driver Code
public 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 structure
class 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 level
hm_min = {}
hm_max = {}
  
# Function to store the min and the
# max index of each nodes in hashmaps
def 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 tree
def 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 Call
print(getMaxWidth(root))
 
# This code is contributed by decode2207.

C#




// C# program for the above approach
using 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 structure
class Node
{
    constructor(item)
    {
        this.data=item;
        this.left=this.right=null;
    }
}
 
// Driver Code
let root;
let maxx = 0;
 
// Stores the position of leftmost
    // and rightmost node in each level
let hm_min=new Map();
let hm_max=new Map();
 
// Function to store the min and the
    // max index of each nodes in hashmaps
function 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 tree
function 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 Code
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
document.write(getMaxWidth(root));
 
// This code is contributed by unknown2108
 
</script>
Output: 
4

 

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




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!