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
Maximum width of a Binary Tree with null values | Set 2
Pre-requisite: Maximum width of a Binary Tree with null value | Set 1 Given a Binary Tree consisting of N nodes, the task is to find the maximum width of the given tree without using recursion, where the maximum width is defined as the maximum of all the widths at each level of the given Tree. Note:
8 min read
Maximum width of a Binary Tree
Given a binary tree, the task is to find the maximum width of the given tree. The width of a tree is the maximum of the widths of all levels. Before solving the problem first, let us understand what we have to do. Binary trees are one of the most common types of trees in computer science. They are a
15+ min read
Maximum width of an N-ary tree
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: 4 Explanation: Width of 0th level is 1. Width of 1st level is 3. Width of 2nd level is 4. There
9 min read
Maximum number in Binary tree of binary values
Given a binary tree consisting of nodes, each containing a binary value of either 0 or 1, the task is to find the maximum decimal number that can be formed by traversing from the root to a leaf node. The maximum number is achieved by concatenating the binary values along the path from the root to a
6 min read
Find the Level of a Binary Tree with Width K
Given a Binary Tree and an integer K, the task is to find the level of the Binary Tree with width K. If multiple levels exists with width K, print the lowest level. If no such level exists, print -1. The width of a level of a Binary tree is defined as the number of nodes between leftmost and the rig
10 min read
Maximum XOR path of a Binary Tree
Given a Binary Tree, the task is to find the maximum of all the XOR value of all the nodes in the path from the root to leaf.Examples: Input: 2 / \ 1 4 / \ 10 8 Output: 11 Explanation: All the paths are: 2-1-10 XOR-VALUE = 9 2-1-8 XOR-VALUE = 11 2-4 XOR-VALUE = 6 Input: 2 / \ 1 4 / \ / \ 10 8 5 10 O
8 min read
Maximum XOR of Two Nodes in a Tree
Given a binary tree, where each node has a binary value, design an efficient algorithm to find the maximum XOR of any two node values in the tree. Examples: Input: 1 / \ 2 3 / \ /4 5 6Output: 7Explanation: 6 XOR 1 = 7 Input: 1 / \ 5 2 / \9 3 Output: 12Explanation: 9 XOR 5 = 12 Naive Approach: A simp
15+ min read
Vertical width of Binary tree | Set 1
Given a Binary tree, the task is to find the vertical width of the Binary tree. The width of a binary tree is the number of vertical paths in the Binary tree. Examples: Input: Output: 6Explanation: In this image, the tree contains 6 vertical lines which are the required width of the tree. Input : 7
14 min read
Vertical width of Binary tree | Set 2
Given a binary tree, find the vertical width of the binary tree. The width of a binary tree is the number of vertical paths. Examples: Input : 7 / \ 6 5 / \ / \ 4 3 2 1 Output : 5 Input : 1 / \ 2 3 / \ / \ 4 5 6 7 \ \ 8 9 Output : 6 Prerequisite: Print Binary Tree in Vertical order In this image, th
5 min read
Find the node whose xor with x gives maximum value
Given a tree, and the weights of all the nodes and an integer x, the task is to find a node i such that weight[i] xor x is maximum.Examples: Input: x = 15 Output: 1 Node 1: 5 xor 15 = 10 Node 2: 10 xor 15 = 5 Node 3: 11 xor 15 = 4 Node 4: 8 xor 15 = 7 Node 5: 6 xor 15 = 9 Approach: Perform dfs on th
5 min read