Maximum width of a Binary Tree with null value
Last Updated :
20 Feb, 2022
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 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.first] -
hm_min[lvl.first] + 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>
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read