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 also called “balanced” trees because all of their nodes have an equal number of children. In this case, we will focus on finding the maximum value of W, which is the width of a binary tree. For example, given a binary tree with root node A, which has two children B and C, where B has two children D and E and C has one child F, the maximum width is 3.
The maximum width of a binary tree is the number of nodes in the tree that have no children. In other words, it is the minimum number of nodes in a tree that can be traversed before you need to make a choice on which node to visit next.
Example:
Input:
1
/ \
2 3
/ \ \
4 5 8
/ \
6 7
Output: 3
Explanation: For the above tree,
width of level 1 is 1,
width of level 2 is 2,
width of level 3 is 3
width of level 4 is 2.
So the maximum width of the tree is 3.
Maximum Width using Level Order Traversal:
To get the width of each level we can use the level order traversal. The maximum among the width of all levels is the required answer.
Level Order Traversal without queue:
This method mainly involves two functions:
- One is to count nodes at a given level (getWidth), and
- The other is to get the maximum width of the tree(getMaxWidth). getMaxWidth() makes use of getWidth() to get the width of all levels starting from the root.
Given below are the pseudo-codes for the mentioned functions.
getMaxWidth(tree)
maxWdth = 0
for i = 1 to height(tree)
width = getWidth(tree, i);
if(width > maxWdth)
maxWdth = width
return maxWidth
getWidth(tree, level)
if tree is NULL then return 0;
if level is 1, then return 1;
else if level greater than 1, then
return getWidth(tree->left, level-1) +
getWidth(tree->right, level-1);
Below is the implementation of the above idea:
C++
#include <bits/stdc++.h>
using namespace std;
class node {
public :
int data;
node* left;
node* right;
node ( int d){
this ->data = d;
this ->left = this ->right = NULL;
}
};
int getWidth(node* root, int level);
int height(node* node);
int getMaxWidth(node* root)
{
int maxWidth = 0;
int width;
int h = height(root);
int i;
for (i = 1; i <= h; i++) {
width = getWidth(root, i);
if (width > maxWidth)
maxWidth = width;
}
return maxWidth;
}
int getWidth(node* root, int level)
{
if (root == NULL)
return 0;
if (level == 1)
return 1;
else if (level > 1)
return getWidth(root->left, level - 1)
+ getWidth(root->right, level - 1);
}
int height(node* node)
{
if (node == NULL)
return 0;
else {
int lHeight = height(node->left);
int rHeight = height(node->right);
return (lHeight > rHeight) ? (lHeight + 1)
: (rHeight + 1);
}
}
int main()
{
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);
cout << "Maximum width is " << getMaxWidth(root)
<< endl;
return 0;
}
|
C
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node* left;
struct node* right;
};
int getWidth( struct node* root, int level);
int height( struct node* node);
struct node* newNode( int data);
int getMaxWidth( struct node* root)
{
int maxWidth = 0;
int width;
int h = height(root);
int i;
for (i = 1; i <= h; i++) {
width = getWidth(root, i);
if (width > maxWidth)
maxWidth = width;
}
return maxWidth;
}
int getWidth( struct node* root, int level)
{
if (root == NULL)
return 0;
if (level == 1)
return 1;
else if (level > 1)
return getWidth(root->left, level - 1)
+ getWidth(root->right, level - 1);
}
int height( struct node* node)
{
if (node == NULL)
return 0;
else {
int lHeight = height(node->left);
int rHeight = height(node->right);
return (lHeight > rHeight) ? (lHeight + 1)
: (rHeight + 1);
}
}
struct node* newNode( int data)
{
struct node* node
= ( struct node*) malloc ( sizeof ( struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return (node);
}
int main()
{
struct node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->right = newNode(8);
root->right->right->left = newNode(6);
root->right->right->right = newNode(7);
printf ( "Maximum width is %d \n" , getMaxWidth(root));
getchar ();
return 0;
}
|
Java
class Node {
int data;
Node left, right;
Node( int item)
{
data = item;
left = right = null ;
}
}
class BinaryTree {
Node root;
int getMaxWidth(Node node)
{
int maxWidth = 0 ;
int width;
int h = height(node);
int i;
for (i = 1 ; i <= h; i++) {
width = getWidth(node, i);
if (width > maxWidth)
maxWidth = width;
}
return maxWidth;
}
int getWidth(Node node, int level)
{
if (node == null )
return 0 ;
if (level == 1 )
return 1 ;
else if (level > 1 )
return getWidth(node.left, level - 1 )
+ getWidth(node.right, level - 1 );
return 0 ;
}
int height(Node node)
{
if (node == null )
return 0 ;
else {
int lHeight = height(node.left);
int rHeight = height(node.right);
return (lHeight > rHeight) ? (lHeight + 1 )
: (rHeight + 1 );
}
}
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
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 );
System.out.println( "Maximum width is "
+ tree.getMaxWidth(tree.root));
}
}
|
Python3
class Node:
def __init__( self , data):
self .data = data
self .left = None
self .right = None
def getMaxWidth(root):
maxWidth = 0
h = height(root)
for i in range ( 1 , h + 1 ):
width = getWidth(root, i)
if (width > maxWidth):
maxWidth = width
return maxWidth
def getWidth(root, level):
if root is None :
return 0
if level = = 1 :
return 1
elif level > 1 :
return (getWidth(root.left, level - 1 ) +
getWidth(root.right, level - 1 ))
def height(node):
if node is None :
return 0
else :
lHeight = height(node.left)
rHeight = height(node.right)
return (lHeight + 1 ) if (lHeight > rHeight) else (rHeight + 1 )
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 )
print ( "Maximum width is %d" % (getMaxWidth(root)))
|
C#
using System;
public class Node {
public int data;
public Node left, right;
public Node( int item)
{
data = item;
left = right = null ;
}
}
public class BinaryTree {
public Node root;
public virtual int getMaxWidth(Node node)
{
int maxWidth = 0;
int width;
int h = height(node);
int i;
for (i = 1; i <= h; i++) {
width = getWidth(node, i);
if (width > maxWidth) {
maxWidth = width;
}
}
return maxWidth;
}
public virtual int getWidth(Node node, int level)
{
if (node == null ) {
return 0;
}
if (level == 1) {
return 1;
}
else if (level > 1) {
return getWidth(node.left, level - 1)
+ getWidth(node.right, level - 1);
}
return 0;
}
public virtual int height(Node node)
{
if (node == null ) {
return 0;
}
else {
int lHeight = height(node.left);
int rHeight = height(node.right);
return (lHeight > rHeight) ? (lHeight + 1)
: (rHeight + 1);
}
}
public static void Main( string [] args)
{
BinaryTree tree = new BinaryTree();
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);
Console.WriteLine( "Maximum width is "
+ tree.getMaxWidth(tree.root));
}
}
|
Javascript
<script>
class Node {
constructor(val) {
this .data = val;
this .left = null ;
this .right = null ;
}
}
var root;
function getMaxWidth(node)
{
var maxWidth = 0;
var width;
var h = height(node);
var i;
for (i = 1; i <= h; i++) {
width = getWidth(node, i);
if (width > maxWidth)
maxWidth = width;
}
return maxWidth;
}
function getWidth(node , level)
{
if (node == null )
return 0;
if (level == 1)
return 1;
else if (level > 1)
return getWidth(node.left, level - 1)
+ getWidth(node.right, level - 1);
return 0;
}
function height(node)
{
if (node == null )
return 0;
else {
var lHeight = height(node.left);
var rHeight = height(node.right);
return (lHeight > rHeight) ? (lHeight + 1)
: (rHeight + 1);
}
}
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);
document.write( "Maximum width is "
+ getMaxWidth(root));
</script>
|
Time Complexity: O(N2) in the worst case.
Auxiliary Space: O(1)
We can use Queue-based level order traversal to optimize the time complexity of this method. The Queue-based level order traversal will take O(N) time in the worst case. Thanks to Nitish, DivyaC, and tech.login.id2 for suggesting this optimization.
Level Order Traversal using Queue
When a queue is used, we can count all the nodes in a level in constant time. This reduces the complexity to be a linear one.
In this method do the following:
- Store all the child nodes at the current level in the queue.
- Count the total number of nodes after the level order traversal for a particular level is completed.
- Since the queue now contains all the nodes of the next level, we can easily find out the total number of nodes in the next level by finding the size of the queue.
- Follow the same procedure for the successive levels.
- Store and update the maximum number of nodes found at each level.
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node* left;
struct Node* right;
Node( int d)
{
this ->data = d;
this ->left = this ->right = NULL;
}
};
int maxWidth( struct Node* root)
{
if (root == NULL)
return 0;
int result = 0;
queue<Node*> q;
q.push(root);
while (!q.empty()) {
int count = q.size();
result = max(count, result);
while (count--) {
Node* temp = q.front();
q.pop();
if (temp->left != NULL)
q.push(temp->left);
if (temp->right != NULL)
q.push(temp->right);
}
}
return result;
}
int main()
{
struct 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);
cout << "Maximum width is " << maxWidth(root) << endl;
return 0;
}
|
Java
import java.util.LinkedList;
import java.util.Queue;
public class maxwidthusingqueue
{
static class node
{
int data;
node left, right;
public node( int data) { this .data = data; }
}
static int maxwidth(node root)
{
if (root == null )
return 0 ;
int maxwidth = 0 ;
Queue<node> q = new LinkedList<>();
q.add(root);
while (!q.isEmpty())
{
int count = q.size();
maxwidth = Math.max(maxwidth, count);
while (count-- > 0 ) {
node temp = q.remove();
if (temp.left != null )
{
q.add(temp.left);
}
if (temp.right != null )
{
q.add(temp.right);
}
}
}
return maxwidth;
}
public static void main(String[] args)
{
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 );
System.out.println( "Maximum width = "
+ maxwidth(root));
}
}
|
Python3
from _collections import deque
class Node:
def __init__( self , data):
self .data = data
self .left = None
self .right = None
def getMaxWidth(root):
if root is None :
return 0
q = deque()
maxWidth = 0
q.append(root)
while q:
count = len (q)
maxWidth = max (count, maxWidth)
while (count is not 0 ):
count = count - 1
temp = q.popleft()
if temp.left is not None :
q.append(temp.left)
if temp.right is not None :
q.append(temp.right)
return maxWidth
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 )
print ( "Maximum width is %d" % (getMaxWidth(root)))
|
C#
using System;
using System.Collections.Generic;
public class maxwidthusingqueue
{
public class node
{
public int data;
public node left, right;
public node( int data) { this .data = data; }
}
static int maxwidth(node root)
{
if (root == null )
return 0;
int maxwidth = 0;
Queue<node> q = new Queue<node>();
q.Enqueue(root);
while (q.Count != 0)
{
int count = q.Count;
maxwidth = Math.Max(maxwidth, count);
while (count-- > 0) {
node temp = q.Dequeue();
if (temp.left != null )
{
q.Enqueue(temp.left);
}
if (temp.right != null )
{
q.Enqueue(temp.right);
}
}
}
return maxwidth;
}
public static void Main(String[] args)
{
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);
Console.WriteLine( "Maximum width = "
+ maxwidth(root));
}
}
|
Javascript
<script>
class node
{
constructor(data) {
this .left = null ;
this .right = null ;
this .data = data;
}
}
function maxwidth(root)
{
if (root == null )
return 0;
let maxwidth = 0;
let q = [];
q.push(root);
while (q.length > 0)
{
let count = q.length;
maxwidth = Math.max(maxwidth, count);
while (count-- > 0) {
let temp = q.shift();
if (temp.left != null )
{
q.push(temp.left);
}
if (temp.right != null )
{
q.push(temp.right);
}
}
}
return maxwidth;
}
let 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);
document.write( "Maximum width is "
+ maxwidth(root));
</script>
|
Time Complexity: O(N) where N is the total number of nodes in the tree. Every node of the tree is processed once and hence the complexity is O(N).
Auxiliary Space: O(w) where w is the maximum width of the tree.
Maximum width Using Preorder Traversal:
The idea behind this approach is to find the level of a node and increment the count of nodes for that level. The number of nodes present at a certain level is the width of that level.
For traversal we can here use the preorder traversal.
Follow the steps mentioned below to implement the approach:
- Create a temporary array count[] of size equal to the height of the tree.
- Initialize all values in count[] as 0.
- Traverse the tree using preorder traversal and fill the entries in count[] so that
- The count[] array contains the count of nodes at each level of the Binary Tree.
- The level with the maximum number of nodes has the maximum width.
- Return the value of that level.
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
class node {
public :
int data;
node* left;
node* right;
node( int d)
{
this ->data = d;
this ->left = this ->right = NULL;
}
};
int height(node* node);
int getMax( int arr[], int n);
void getMaxWidthRecur(node* root, int count[], int level);
int getMaxWidth(node* root)
{
int width;
int h = height(root);
int * count = new int [h];
int level = 0;
getMaxWidthRecur(root, count, level);
return getMax(count, h);
}
void getMaxWidthRecur(node* root,
int count[], int level)
{
if (root) {
count[level]++;
getMaxWidthRecur(root->left, count, level + 1);
getMaxWidthRecur(root->right, count, level + 1);
}
}
int height(node* node)
{
if (node == NULL)
return 0;
else {
int lHeight = height(node->left);
int rHeight = height(node->right);
return (lHeight > rHeight) ? (lHeight + 1)
: (rHeight + 1);
}
}
int getMax( int arr[], int n)
{
int max = arr[0];
int i;
for (i = 0; i < n; i++) {
if (arr[i] > max)
max = arr[i];
}
return max;
}
int main()
{
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);
cout << "Maximum width is " << getMaxWidth(root)
<< endl;
return 0;
}
|
C
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node* left;
struct node* right;
};
int height( struct node* node);
struct node* newNode( int data);
int getMax( int arr[], int n);
void getMaxWidthRecur( struct node* root, int count[],
int level);
int getMaxWidth( struct node* root)
{
int width;
int h = height(root);
int * count = ( int *) calloc ( sizeof ( int ), h);
int level = 0;
getMaxWidthRecur(root, count, level);
return getMax(count, h);
}
void getMaxWidthRecur( struct node* root, int count[],
int level)
{
if (root) {
count[level]++;
getMaxWidthRecur(root->left, count, level + 1);
getMaxWidthRecur(root->right, count, level + 1);
}
}
int height( struct node* node)
{
if (node == NULL)
return 0;
else {
int lHeight = height(node->left);
int rHeight = height(node->right);
return (lHeight > rHeight) ? (lHeight + 1)
: (rHeight + 1);
}
}
struct node* newNode( int data)
{
struct node* node
= ( struct node*) malloc ( sizeof ( struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return (node);
}
int getMax( int arr[], int n)
{
int max = arr[0];
int i;
for (i = 0; i < n; i++) {
if (arr[i] > max)
max = arr[i];
}
return max;
}
int main()
{
struct node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->right = newNode(8);
root->right->right->left = newNode(6);
root->right->right->right = newNode(7);
printf ( "Maximum width is %d \n" , getMaxWidth(root));
getchar ();
return 0;
}
|
Java
class Node {
int data;
Node left, right;
Node( int item)
{
data = item;
left = right = null ;
}
}
class BinaryTree {
Node root;
int getMaxWidth(Node node)
{
int width;
int h = height(node);
int count[] = new int [ 10 ];
int level = 0 ;
getMaxWidthRecur(node, count, level);
return getMax(count, h);
}
void getMaxWidthRecur(Node node, int count[], int level)
{
if (node != null ) {
count[level]++;
getMaxWidthRecur(node.left, count, level + 1 );
getMaxWidthRecur(node.right, count, level + 1 );
}
}
int height(Node node)
{
if (node == null )
return 0 ;
else {
int lHeight = height(node.left);
int rHeight = height(node.right);
return (lHeight > rHeight) ? (lHeight + 1 )
: (rHeight + 1 );
}
}
int getMax( int arr[], int n)
{
int max = arr[ 0 ];
int i;
for (i = 0 ; i < n; i++) {
if (arr[i] > max)
max = arr[i];
}
return max;
}
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
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 );
System.out.println( "Maximum width is "
+ tree.getMaxWidth(tree.root));
}
}
|
Python3
class Node:
def __init__( self , data):
self .data = data
self .left = None
self .right = None
def getMaxWidth(root):
h = height(root)
count = [ 0 ] * h
level = 0
getMaxWidthRecur(root, count, level)
return getMax(count, h)
def getMaxWidthRecur(root, count, level):
if root is not None :
count[level] + = 1
getMaxWidthRecur(root.left, count, level + 1 )
getMaxWidthRecur(root.right, count, level + 1 )
def height(node):
if node is None :
return 0
else :
lHeight = height(node.left)
rHeight = height(node.right)
return (lHeight + 1 ) if (lHeight > rHeight) else (rHeight + 1 )
def getMax(count, n):
max = count[ 0 ]
for i in range ( 1 , n):
if (count[i] > max ):
max = count[i]
return max
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 )
print ( "Maximum width is %d" % (getMaxWidth(root)))
|
C#
using System;
public class Node
{
public int data;
public Node left, right;
public Node( int item)
{
data = item;
left = right = null ;
}
}
public class BinaryTree
{
Node root;
int getMaxWidth(Node node)
{
int width;
int h = height(node);
int [] count = new int [10];
int level = 0;
getMaxWidthRecur(node, count, level);
return getMax(count, h);
}
void getMaxWidthRecur(Node node, int [] count, int level)
{
if (node != null )
{
count[level]++;
getMaxWidthRecur(node.left, count, level + 1);
getMaxWidthRecur(node.right, count, level + 1);
}
}
int height(Node node)
{
if (node == null )
return 0;
else
{
int lHeight = height(node.left);
int rHeight = height(node.right);
return (lHeight > rHeight) ? (lHeight + 1)
: (rHeight + 1);
}
}
int getMax( int [] arr, int n)
{
int max = arr[0];
int i;
for (i = 0; i < n; i++)
{
if (arr[i] > max)
max = arr[i];
}
return max;
}
public static void Main(String[] args)
{
BinaryTree tree = new BinaryTree();
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);
Console.WriteLine( "Maximum width is "
+ tree.getMaxWidth(tree.root));
}
}
|
Javascript
<script>
class Node {
constructor(val) {
this .data = val;
this .left = null ;
this .right = null ;
}
}
var root;
function getMaxWidth(node)
{
var width;
var h = height(node);
var count = Array(10).fill(0);
var level = 0;
getMaxWidthRecur(node, count, level);
return getMax(count, h);
}
function getMaxWidthRecur(node , count , level)
{
if (node != null ) {
count[level]++;
getMaxWidthRecur(node.left, count, level + 1);
getMaxWidthRecur(node.right, count, level + 1);
}
}
function height(node)
{
if (node == null )
return 0;
else {
var lHeight = height(node.left);
var rHeight = height(node.right);
return (lHeight > rHeight) ? (lHeight + 1)
: (rHeight + 1);
}
}
function getMax(arr , n)
{
var max = arr[0];
var i;
for (i = 0; i < n; i++) {
if (arr[i] > max)
max = arr[i];
}
return max;
}
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);
document.write( "Maximum width is "
+ getMaxWidth(root));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(h) where h is the height of the tree.
Thanks to Raja and Jagdish for suggesting this method.
Please write comments if you find the above code/algorithm incorrect, or find better ways to solve the same problem.
Maximum width Using a Special form of level Order Traversal:
We will perform a special level order traversal with two loops where inner loops traverses the nodes of a single level. This is to ensure that we can do our calculations once a single level is traversed. In the traversal, we will assign an index to a node.
Below is the implementation of the above Approach:
C++
#include <bits/stdc++.h>
using namespace std;
struct node {
int data;
struct node * left, * right;
};
int widthOfBinaryTree(node * root) {
if (!root)
return 0;
int ans = 0;
queue < pair < node * , int >> q;
q.push({
root,
0
});
while (!q.empty()) {
int size = q.size();
int curMin = q.front().second;
int leftMost, rightMost;
for ( int i = 0; i < size; i++) {
int cur_id = q.front().second - curMin;
node * temp = q.front().first;
q.pop();
if (i == 0) leftMost = cur_id;
if (i == size - 1) rightMost = cur_id;
if (temp -> left)
q.push({
temp -> left,
cur_id * 2 + 1
});
if (temp -> right)
q.push({
temp -> right,
cur_id * 2 + 2
});
}
ans = max(ans, rightMost - leftMost + 1);
}
return ans;
}
struct node * newNode( int data) {
struct node * node = ( struct node * ) malloc ( sizeof ( struct node));
node -> data = data;
node -> left = NULL;
node -> right = NULL;
return (node);
}
int main() {
struct node * root = newNode(1);
root -> left = newNode(3);
root -> left -> left = newNode(5);
root -> left -> left -> left = newNode(7);
root -> right = newNode(2);
root -> right -> right = newNode(4);
root -> right -> right -> right = newNode(6);
int maxWidth = widthOfBinaryTree(root);
cout << "The maximum width of the Binary Tree is " << maxWidth;
return 0;
}
|
Java
import java.util.*;
class TreeNode {
int data;
TreeNode left, right;
TreeNode( int data)
{
this .data=data;
left= null ;
right= null ;
}
}
class Pair {
TreeNode node;
int num;
Pair(TreeNode _node, int _num) {
num = _num;
node = _node;
}
}
class Solution {
public static int widthOfBinaryTree(TreeNode root) {
if (root == null ) return 0 ;
int ans = 0 ;
Queue<Pair> q = new LinkedList<>();
q.offer( new Pair(root, 0 ));
while (!q.isEmpty()){
int size = q.size();
int mmin = q.peek().num;
int first = 0 ,last = 0 ;
for ( int i= 0 ; i<size; i++){
int cur_id = q.peek().num-mmin;
TreeNode node = q.peek().node;
q.poll();
if (i== 0 ) first = cur_id;
if (i==size- 1 ) last = cur_id;
if (node.left != null )
q.offer( new Pair(node.left, cur_id* 2 + 1 ));
if (node.right != null )
q.offer( new Pair(node.right, cur_id* 2 + 2 ));
}
ans = Math.max(ans, last-first+ 1 );
}
return ans;
}
public static void main(String args[]) {
TreeNode root = new TreeNode( 1 );
root . left = new TreeNode( 3 );
root . left . left = new TreeNode( 5 );
root . left . left . left = new TreeNode( 7 );
root . right = new TreeNode( 2 );
root . right . right = new TreeNode( 4 );
root . right . right . right = new TreeNode( 6 );
int maxWidth = widthOfBinaryTree(root);
System.out.println( "The maximum width of the Binary Tree is " +maxWidth);
}
}
|
Python3
from collections import deque
class Node:
def __init__( self , data):
self .data = data
self .left = None
self .right = None
def widthOfBinaryTree(root):
if not root:
return 0
ans = 0
q = deque([(root, 0 )])
while q:
size = len (q)
cur_min = q[ 0 ][ 1 ]
left_most, right_most = None , None
for i in range (size):
cur_id = q[ 0 ][ 1 ] - cur_min
temp, _ = q.popleft()
if i = = 0 :
left_most = cur_id
if i = = size - 1 :
right_most = cur_id
if temp.left:
q.append((temp.left, cur_id * 2 + 1 ))
if temp.right:
q.append((temp.right, cur_id * 2 + 2 ))
ans = max (ans, right_most - left_most + 1 )
return ans
def newNode(data):
node = Node(data)
return node
def main():
root = newNode( 1 )
root.left = newNode( 3 )
root.left.left = newNode( 5 )
root.left.left.left = newNode( 7 )
root.right = newNode( 2 )
root.right.right = newNode( 4 )
root.right.right.right = newNode( 6 )
maxWidth = widthOfBinaryTree(root)
print ( "The maximum width of the Binary Tree is" , maxWidth)
if __name__ = = "__main__" :
main()
|
C#
using System;
using System.Collections.Generic;
public class Node
{
public int Data;
public Node Left;
public Node Right;
}
public class BinaryTree
{
public static int WidthOfBinaryTree(Node root)
{
if (root == null )
return 0;
int maxWidth = 0;
Queue<Tuple<Node, int >> queue = new Queue<Tuple<Node, int >>();
queue.Enqueue( new Tuple<Node, int >(root, 0));
while (queue.Count > 0)
{
int size = queue.Count;
int curMin = queue.Peek().Item2;
int leftMost = 0, rightMost = 0;
for ( int i = 0; i < size; i++)
{
Tuple<Node, int > current = queue.Dequeue();
int curId = current.Item2 - curMin;
Node temp = current.Item1;
if (i == 0)
leftMost = curId;
if (i == size - 1)
rightMost = curId;
if (temp.Left != null )
queue.Enqueue( new Tuple<Node, int >(temp.Left, curId * 2 + 1));
if (temp.Right != null )
queue.Enqueue( new Tuple<Node, int >(temp.Right, curId * 2 + 2));
}
maxWidth = Math.Max(maxWidth, rightMost - leftMost + 1);
}
return maxWidth;
}
}
public class GFG
{
public static void Main()
{
Node root = new Node { Data = 1 };
root.Left = new Node { Data = 3 };
root.Left.Left = new Node { Data = 5 };
root.Left.Left.Left = new Node { Data = 7 };
root.Right = new Node { Data = 2 };
root.Right.Right = new Node { Data = 4 };
root.Right.Right.Right = new Node { Data = 6 };
int maxWidth = BinaryTree.WidthOfBinaryTree(root);
Console.WriteLine( "The maximum width of the Binary Tree is " + maxWidth);
}
}
|
Javascript
class Node {
constructor(data) {
this .data = data;
this .left = null ;
this .right = null ;
}
}
function widthOfBinaryTree(root) {
if (!root) {
return 0;
}
let maxWidth = 0;
const queue = [[root, 0]];
while (queue.length > 0) {
const size = queue.length;
const curMin = queue[0][1];
let leftMost, rightMost;
for (let i = 0; i < size; i++) {
const [temp, curId] = queue.shift();
if (i === 0) {
leftMost = curId;
}
if (i === size - 1) {
rightMost = curId;
}
if (temp.left) {
queue.push([temp.left, curId * 2 + 1]);
}
if (temp.right) {
queue.push([temp.right, curId * 2 + 2]);
}
}
maxWidth = Math.max(maxWidth, rightMost - leftMost + 1);
}
return maxWidth;
}
function newNode(data) {
const node = new Node(data);
return node;
}
const root = newNode(1);
root.left = newNode(3);
root.left.left = newNode(5);
root.left.left.left = newNode(7);
root.right = newNode(2);
root.right.right = newNode(4);
root.right.right.right = newNode(6);
const maxWidth = widthOfBinaryTree(root);
console.log( "The maximum width of the Binary Tree is " + maxWidth);
|
OutputThe maximum width of the Binary Tree is 8
Time Complexity : O(N)
Space Complexity : O(N)