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: 6
Explanation: In this image, the tree contains 6 vertical lines which are the required width of the tree.
Input :
7
/ \
6 5
/ \ / \
4 3 2 1
Output : 5
Input:
1
/ \
2 3
/ \ / \
4 5 6 7
\ \
8 9
Output : 6
Approach:
Take inorder traversal and then take a temp variable to keep the track of unique vertical paths. when moving to left of the node then temp decreases by one and if goes to right then temp value increases by one. If the minimum is greater than temp, then update minimum = temp and if maximum less than temp then update maximum = temp. The vertical width of the tree will be equal to abs(minimum ) + maximum.
Follow the below steps to Implement the idea:
- Initialize a minimum and maximum variable to track the left-most and right-most index.
- Run Depth-first search traversal and maintain the current horizontal index curr, for root curr = 0.
- Traverse left subtree with curr = curr-1
- Update maximum with curr if curr > maximum.
- Update minimum with curr if curr < minimum.
- Traverse right subtree with curr = curr + 1.
- Print the vertical width of the tree i.e. abs(minimum ) + maximum.
Below is the Implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node *left, *right;
};
void lengthUtil(Node* root, int & maximum, int & minimum,
int curr = 0)
{
if (root == NULL)
return ;
lengthUtil(root->left, maximum, minimum, curr - 1);
if (minimum > curr)
minimum = curr;
if (maximum < curr)
maximum = curr;
lengthUtil(root->right, maximum, minimum, curr + 1);
}
int getLength(Node* root)
{
int maximum = 0, minimum = 0;
lengthUtil(root, maximum, minimum, 0);
return ( abs (minimum) + maximum) + 1;
}
Node* newNode( int data)
{
Node* curr = new Node;
curr->data = data;
curr->left = curr->right = NULL;
return curr;
}
int main()
{
Node* root = newNode(7);
root->left = newNode(6);
root->right = newNode(5);
root->left->left = newNode(4);
root->left->right = newNode(3);
root->right->left = newNode(2);
root->right->right = newNode(1);
cout << getLength(root) << "\n" ;
return 0;
}
|
Java
import java.util.*;
class GFG {
static class Node {
int data;
Node left, right;
};
static int maximum = 0 , minimum = 0 ;
static void lengthUtil(Node root, int curr)
{
if (root == null )
return ;
lengthUtil(root.left, curr - 1 );
if (minimum > curr)
minimum = curr;
if (maximum < curr)
maximum = curr;
lengthUtil(root.right, curr + 1 );
}
static int getLength(Node root)
{
maximum = 0 ;
minimum = 0 ;
lengthUtil(root, 0 );
return (Math.abs(minimum) + maximum) + 1 ;
}
static Node newNode( int data)
{
Node curr = new Node();
curr.data = data;
curr.left = curr.right = null ;
return curr;
}
public static void main(String[] args)
{
Node root = newNode( 7 );
root.left = newNode( 6 );
root.right = newNode( 5 );
root.left.left = newNode( 4 );
root.left.right = newNode( 3 );
root.right.left = newNode( 2 );
root.right.right = newNode( 1 );
System.out.println(getLength(root));
}
}
|
Python3
class newNode:
def __init__( self , data):
self .data = data
self .left = self .right = None
def lengthUtil(root, maximum, minimum, curr = 0 ):
if (root = = None ):
return
lengthUtil(root.left, maximum,
minimum, curr - 1 )
if (minimum[ 0 ] > curr):
minimum[ 0 ] = curr
if (maximum[ 0 ] < curr):
maximum[ 0 ] = curr
lengthUtil(root.right, maximum,
minimum, curr + 1 )
def getLength(root):
maximum = [ 0 ]
minimum = [ 0 ]
lengthUtil(root, maximum, minimum, 0 )
return ( abs (minimum[ 0 ]) + maximum[ 0 ]) + 1
if __name__ = = '__main__' :
root = newNode( 7 )
root.left = newNode( 6 )
root.right = newNode( 5 )
root.left.left = newNode( 4 )
root.left.right = newNode( 3 )
root.right.left = newNode( 2 )
root.right.right = newNode( 1 )
print (getLength(root))
|
C#
using System;
class GFG {
public class Node {
public int data;
public Node left, right;
};
static int maximum = 0, minimum = 0;
static void lengthUtil(Node root, int curr)
{
if (root == null )
return ;
lengthUtil(root.left, curr - 1);
if (minimum > curr)
minimum = curr;
if (maximum < curr)
maximum = curr;
lengthUtil(root.right, curr + 1);
}
static int getLength(Node root)
{
maximum = 0;
minimum = 0;
lengthUtil(root, 0);
return (Math.Abs(minimum) + maximum) + 1;
}
static Node newNode( int data)
{
Node curr = new Node();
curr.data = data;
curr.left = curr.right = null ;
return curr;
}
public static void Main(String[] args)
{
Node root = newNode(7);
root.left = newNode(6);
root.right = newNode(5);
root.left.left = newNode(4);
root.left.right = newNode(3);
root.right.left = newNode(2);
root.right.right = newNode(1);
Console.WriteLine(getLength(root));
}
}
|
Javascript
<script>
class newNode{
constructor(data){
this .data = data
this .left = this .right = null
}
}
function lengthUtil(root, maximum, minimum, curr = 0){
if (root == null )
return
lengthUtil(root.left, maximum,
minimum, curr - 1)
if (minimum[0] > curr)
minimum[0] = curr
if (maximum[0] <curr)
maximum[0] = curr
lengthUtil(root.right, maximum,
minimum, curr + 1)
}
function getLength(root)
{
let maximum = [0]
let minimum = [0]
lengthUtil(root, maximum, minimum, 0)
return (Math.abs(minimum[0]) + maximum[0]) + 1
}
root = new newNode(7)
root.left = new newNode(6)
root.right = new newNode(5)
root.left.left = new newNode(4)
root.left.right = new newNode(3)
root.right.left = new newNode(2)
root.right.right = new newNode(1)
document.write(getLength(root), "</br>" )
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(h) where h is the height of the binary tree. This much space is needed for recursive calls.
Below is the idea to solve the problem:
Create a class to store the node and the horizontal level of the node. The horizontal level of left node will be 1 less than its parent, and horizontal level of the right node will be 1 more than its parent. We create a minLevel variable to store the minimum horizontal level or the leftmost node in the tree, and a maxLevel variable to store the maximum horizontal level or the rightmost node in the tree. Traverse the tree in level order and store the minLevel and maxLevel. In the end, print sum of maxLevel and absolute value of minLevel which is the vertical width of the tree.
Follow the below steps to Implement the idea:
- Initialize two variables maxLevel = 0 and minLevel = 0 and queue Q of pair of the type (Node*, Integer).
- Push (root, 0) in Q.
- Run while loop till Q is not empty
- Store the front node of the Queue in cur and the current horizontal level in count.
- If curr->left is not null then push (root->left, count-1) and update minLevel with min(minLevel, count-1).
- If curr->right is not null then push (root->right, count+1) and update maxLevel with max(maxLevel, count+1).
- Print maxLevel + abs(minLevel) + 1.
Below is the Implementation of the above approach:
C++
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
struct Node {
int data;
struct Node* left;
struct Node* right;
Node( int x)
{
data = x;
left = right = NULL;
}
};
int verticalWidth(Node* root)
{
if (root == NULL)
return 0;
int maxLevel = 0, minLevel = 0;
queue<pair<Node*, int > > q;
q.push({ root, 0 });
while (q.empty() != true ) {
Node* cur = q.front().first;
int count = q.front().second;
q.pop();
if (cur->left) {
minLevel = min(minLevel,
count - 1);
q.push({ cur->left, count - 1 });
}
if (cur->right) {
maxLevel = max(maxLevel,
count + 1);
q.push({ cur->right, count + 1 });
}
}
return maxLevel + abs (minLevel)
+ 1;
}
int main()
{
Node* root = new Node(7);
root->left = new Node(6);
root->right = new Node(5);
root->left->left = new Node(4);
root->left->right = new Node(3);
root->right->left = new Node(2);
root->right->right = new Node(1);
cout << "Vertical width is : " << verticalWidth(root)
<< endl;
return 0;
}
|
Java
import java.util.*;
class GFG {
static class Node {
int data;
Node left, right;
};
static class Pair {
Node node;
int level;
Pair(Node node, int level)
{
this .node = node;
this .level = level;
}
}
static int maxLevel = 0 , minLevel = 0 ;
static void lengthUtil(Node root)
{
Queue<Pair> q = new ArrayDeque<>();
q.add( new Pair(root, 0 ));
while (q.size() > 0 ) {
Pair rem = q.remove();
if (rem.node.left != null ) {
q.add(
new Pair(rem.node.left, rem.level - 1 ));
minLevel
= Math.min(minLevel, rem.level - 1 );
}
if (rem.node.right != null ) {
q.add( new Pair(rem.node.right,
rem.level + 1 ));
maxLevel
= Math.max(minLevel, rem.level + 1 );
}
}
}
static int getLength(Node root)
{
maxLevel = 0 ;
minLevel = 0 ;
lengthUtil(root);
return (Math.abs(minLevel) + maxLevel) + 1 ;
}
static Node newNode( int data)
{
Node curr = new Node();
curr.data = data;
curr.left = curr.right = null ;
return curr;
}
public static void main(String[] args)
{
Node root = newNode( 7 );
root.left = newNode( 6 );
root.right = newNode( 5 );
root.left.left = newNode( 4 );
root.left.right = newNode( 3 );
root.right.left = newNode( 2 );
root.right.right = newNode( 1 );
System.out.println(getLength(root));
}
}
|
Python3
class Node:
def __init__( self , data):
self .data = data
self .left = None
self .right = None
def verticalWidth(root):
if root = = None :
return 0
maxLevel = 0
minLevel = 0
q = []
q.append([root, 0 ])
while len (q) ! = 0 :
cur, count = q.pop( 0 )
if cur.left:
minLevel = min (minLevel, count - 1 )
q.append([cur.left, count - 1 ])
if cur.right:
maxLevel = max (maxLevel, count + 1 )
q.append([cur.right, count + 1 ])
return maxLevel + abs (minLevel) + 1
root = Node( 7 )
root.left = Node( 6 )
root.right = Node( 5 )
root.left.left = Node( 4 )
root.left.right = Node( 3 )
root.right.left = Node( 2 )
root.right.right = Node( 1 )
print ( "Vertical width is : " , verticalWidth(root))
|
C#
using System;
using System.Collections;
public class GFG {
class Node {
public int data;
public Node left, right;
};
class Pair {
public Node node;
public int level;
public Pair(Node node, int level)
{
this .node = node;
this .level = level;
}
}
static int maxLevel = 0, minLevel = 0;
static void lengthUtil(Node root)
{
Queue q = new Queue();
q.Enqueue( new Pair(root, 0));
while (q.Count > 0) {
Pair rem = (Pair)q.Dequeue();
if (rem.node.left != null ) {
q.Enqueue(
new Pair(rem.node.left, rem.level - 1));
minLevel
= Math.Min(minLevel, rem.level - 1);
}
if (rem.node.right != null ) {
q.Enqueue( new Pair(rem.node.right,
rem.level + 1));
maxLevel
= Math.Max(minLevel, rem.level + 1);
}
}
}
static int getLength(Node root)
{
maxLevel = 0;
minLevel = 0;
lengthUtil(root);
return (Math.Abs(minLevel) + maxLevel) + 1;
}
static Node newNode( int data)
{
Node curr = new Node();
curr.data = data;
curr.left = curr.right = null ;
return curr;
}
static public void Main()
{
Node root = newNode(7);
root.left = newNode(6);
root.right = newNode(5);
root.left.left = newNode(4);
root.left.right = newNode(3);
root.right.left = newNode(2);
root.right.right = newNode(1);
Console.WriteLine(getLength(root));
}
}
|
Javascript
class Node {
constructor(x) {
this .data = x;
this .left = null ;
this .right = null ;
}
}
function verticalWidth(root) {
if (!root) {
return 0;
}
let maxLevel = 0;
let minLevel = 0;
const q = [];
q.push([root, 0]);
while (q.length !== 0) {
const [cur, count] = q.shift();
if (cur.left) {
minLevel = Math.min(minLevel, count - 1);
q.push([cur.left, count - 1]);
}
if (cur.right) {
maxLevel = Math.max(maxLevel, count + 1);
q.push([cur.right, count + 1]);
}
}
return maxLevel + Math.abs(minLevel) + 1;
}
const root = new Node(7);
root.left = new Node(6);
root.right = new Node(5);
root.left.left = new Node(4);
root.left.right = new Node(3);
root.right.left = new Node(2);
root.right.right = new Node(1);
console.log( "Vertical width is: " , verticalWidth(root));
|
Time Complexity: O(n). This much time is needed to traverse the tree.
Auxiliary Space: O(n). This much space is needed to maintain the queue.
Last Updated :
11 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...