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: 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:
1 // width = 1
/ \
2 3 // width = 2 – 1 + 1= 2
/ \ \
4 5 8 // width = 6 – 3 + 1 = 4
/ \
6 7 // width = 8 – 7 + 1 = 2
So, the answer is 4
Input:
1
/
2
/
3
Output: 1
Approach: In this approach, the main idea is to use level order traversal and to give an id to all nodes according to their parent which will help to find the width of a particular level. Ids are distributed in this particular order:
[node, id: i]
/ \
[left child, id: (i * 2 +1)] [right child, id: (i * 2 + 2)]
Now the width of each level can be calculated using the formula
Width of level i = (id of first node at level i) – (id of last node at level i) +1
Illustration: For example, use the first example provided here.
{1,0} // width = 1
/ \
{2,1} {3,2} // width = 2 – 1 + 1= 2
/ \ \
{4,3} {5,4} {8,6} // width = 6 – 3 + 1 = 4
/ \
{6,7} {7,8} // width = 8 – 7 + 1 = 2
So, the answer is 4
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node *left, *right;
Node( int item)
{
data = item;
left = right = NULL;
}
};
int getMaxWidth(Node* root)
{
if (root == NULL) {
return 0;
}
queue<pair<Node*, int > > q;
q.push({ root, 0 });
int maxWidth = 1;
while (!q.empty()) {
int size = q.size();
int first, last;
for ( int i = 0; i < size; i++) {
Node* temp = q.front().first;
int id = q.front().second;
q.pop();
if (i == 0) {
first = id;
}
if (i == size - 1) {
last = id;
};
if (temp->left)
q.push({ temp->left,
id * 2 + 1 });
if (temp->right)
q.push({ temp->right,
id * 2 + 2 });
}
maxWidth = max(maxWidth,
last - first + 1);
}
return maxWidth;
}
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 << getMaxWidth(root);
return 0;
}
|
Java
import java.util.LinkedList;
import java.util.Queue;
class GFG {
public static class Node {
int data;
Node left;
Node right;
public Node( int item) {
this .data = item;
this .left = this .right = null ;
}
};
public static class Pair {
Node first;
int second;
public Pair(Node n, int i) {
this .first = n;
this .second = i;
}
}
static int getMaxWidth(Node root) {
if (root == null ) {
return 0 ;
}
Queue<Pair> q = new LinkedList<Pair>();
q.add( new Pair(root, 0 ));
int maxWidth = 1 ;
while (!q.isEmpty()) {
int size = q.size();
int first = 0 , last = 0 ;
for ( int i = 0 ; i < size; i++) {
Node temp = q.peek().first;
int id = q.peek().second;
q.remove();
if (i == 0 ) {
first = id;
}
if (i == size - 1 ) {
last = id;
}
;
if (temp.left != null )
q.add( new Pair(temp.left, id * 2 + 1 ));
if (temp.right != null )
q.add( new Pair(temp.right, id * 2 + 2 ));
}
maxWidth = Math.max(maxWidth, last - first + 1 );
}
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(getMaxWidth(root));
}
}
|
Python3
class Node:
def __init__( self , item):
self .data = item
self .left = self .right = None
def getMaxWidth(root):
if (root = = None ):
return 0
q = []
q.append([root, 0 ])
maxWidth = 1
while ( len (q)):
size = len (q)
first = None
last = None
for i in range (size):
temp = q[ 0 ][ 0 ]
id = q[ 0 ][ 1 ]
q.pop( 0 )
if (i = = 0 ):
first = id
if (i = = size - 1 ):
last = id
if (temp.left):
q.append([temp.left, id * 2 + 1 ])
if (temp.right):
q.append([temp.right, id * 2 + 2 ])
maxWidth = max (maxWidth, last - first + 1 )
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 (getMaxWidth(root))
|
C#
using System;
using System.Collections.Generic;
public class GFG {
public class Node {
public int data;
public Node left;
public Node right;
public Node( int item) {
this .data = item;
this .left = this .right = null ;
}
};
public class Pair {
public Node first;
public int second;
public Pair(Node n, int i) {
this .first = n;
this .second = i;
}
}
static int getMaxWidth(Node root) {
if (root == null ) {
return 0;
}
Queue<Pair> q = new Queue<Pair>();
q.Enqueue( new Pair(root, 0));
int maxWidth = 1;
while (q.Count!=0) {
int size = q.Count;
int first = 0, last = 0;
for ( int i = 0; i < size; i++) {
Node temp = q.Peek().first;
int id = q.Peek().second;
q.Dequeue();
if (i == 0) {
first = id;
}
if (i == size - 1) {
last = id;
}
;
if (temp.left != null )
q.Enqueue( new Pair(temp.left, id * 2 + 1));
if (temp.right != null )
q.Enqueue( new Pair(temp.right, id * 2 + 2));
}
maxWidth = Math.Max(maxWidth, last - first + 1);
}
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(getMaxWidth(root));
}
}
|
Javascript
<script>
class Node {
constructor(item) {
this .data = item;
this .left = this .right = null ;
}
};
function getMaxWidth(root) {
if (root == null ) {
return 0;
}
let q = [];
q.push([root, 0]);
let maxWidth = 1;
while (q.length) {
let size = q.length;
let first, last;
for (let i = 0; i < size; i++) {
let temp = q[0][0];
let id = q[0][1];
q.shift();
if (i == 0) {
first = id;
}
if (i == size - 1) {
last = id;
};
if (temp.left)
q.push([temp.left, id * 2 + 1]);
if (temp.right)
q.push([temp.right, id * 2 + 2]);
}
maxWidth = Math.max(maxWidth, last - first + 1);
}
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(getMaxWidth(root));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Last Updated :
07 Apr, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...