Maximum width of a Binary Tree with null values | Set 2
Last Updated :
07 Apr, 2022
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++
// 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;
}
};
// Function to find the width
// of the given tree
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();
// First Node
if (i == 0) {
first = id;
}
// Last Node
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;
}
// Driver Code
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);
// Function Call
cout << getMaxWidth(root);
return 0;
}
Java
// Java program for the above approach
import java.util.LinkedList;
import java.util.Queue;
class GFG {
// Tree Node structure
public static class Node {
int data;
Node left;
Node right;
// Constructor
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;
}
}
// Function to find the width
// of the given tree
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();
// First Node
if (i == 0) {
first = id;
}
// Last Node
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;
}
// Driver Code
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);
// Function Call
System.out.println(getMaxWidth(root));
}
}
// This code is contributed by saurabh_jaiswal.
Python3
# Python program for the above approach
# Tree Node structure
class Node:
# Constructor
def __init__(self, item):
self.data = item
self.left = self.right = None
# Function to find the width
# of the given tree
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)
# First Node
if (i == 0):
first = id
# Last Node
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
# Driver Code
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 Saurabh jaiswal
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
public class GFG {
// Tree Node structure
public class Node {
public int data;
public Node left;
public Node right;
// Constructor
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;
}
}
// Function to find the width
// of the given tree
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();
// First Node
if (i == 0) {
first = id;
}
// Last Node
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;
}
// Driver Code
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);
// Function Call
Console.WriteLine(getMaxWidth(root));
}
}
// This code is contributed by shikhasingrajput
JavaScript
<script>
// Javascript program for the above approach
// Tree Node structure
class Node {
// Constructor
constructor(item) {
this.data = item;
this.left = this.right = null;
}
};
// Function to find the width
// of the given tree
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();
// First Node
if (i == 0) {
first = id;
}
// Last Node
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;
}
// Driver Code
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);
// Function Call
document.write(getMaxWidth(root));
// This code is contributed by gfgking.
</script>
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
Maximum width of a Binary Tree with null value
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
11 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
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 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
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
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
Find the node with maximum value in a Binary Search Tree using recursion
Given a Binary Search Tree, the task is to find the node with maximum value. Examples: Input: Output: 22 Approach: Just traverse the node from root to right recursively until right is NULL. The node whose right is NULL is the node with the maximum value. Below is the implementation of the above appr
7 min read
Maximum average of subtree values in a given Binary Tree
Given a Binary Tree consisting of N nodes, the task to find the maximum average of values of nodes of any subtree. Examples: Input: 5 / \ 3 8 Output: 8Explanation:Average of values of subtree of node 5 = (5 + 3 + 8) / 3 = 5.33Average of values of subtree of node 3 = 3 / 1 = 3Average of values of sub
9 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