Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Tree
  • Practice Tree
  • MCQs on Tree
  • Tutorial on Tree
  • Types of Trees
  • Basic operations
  • Tree Traversal
  • Binary Tree
  • Complete Binary Tree
  • Ternary Tree
  • Binary Search Tree
  • Red-Black Tree
  • AVL Tree
  • Full Binary Tree
  • B-Tree
  • Advantages & Disadvantages
Open In App
Next Article:
Vertical width of Binary tree | Set 1
Next article icon

Vertical width of Binary tree | Set 2

Last Updated : 18 Nov, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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, the tree contains 6 vertical lines which is the required width of tree.

Approach: 

In this approach, we use the approach for printing vertical View of binary tree. Store the horizontal distances in a set and return 1 + highest horizontal distance - lowest horizontal distance. 1 is added to consider horizontal distance 0 as well. While going left, do hd - 1 and for right do hd + 1. We insert all possible distances in a hash table and finally return size of the hash table.

Implementation:

C++
// CPP code to find vertical // width of a binary tree #include <bits/stdc++.h> using namespace std;  // Tree class class Node { public :     int data;     Node *left, *right;      // Constructor     Node(int data_new)     {         data = data_new;         left = right = NULL;     } };  // Function to fill hd in set. void fillSet(Node* root, unordered_set<int>& s,                                        int hd) {     if (!root)         return;      fillSet(root->left, s, hd - 1);     s.insert(hd);     fillSet(root->right, s, hd + 1); }  int verticalWidth(Node* root) {     unordered_set<int> s;      // Third parameter is horizontal     // distance     fillSet(root, s, 0);      return s.size(); }  int main() {     Node* root = NULL;      // Creating the above tree     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->left = new Node(6);     root->right->right = new Node(7);     root->right->left->right = new Node(8);     root->right->right->right = new Node(9);      cout << verticalWidth(root) << "\n";      return 0; } 
Java
/* Java code to find the vertical width of a binary tree */ import java.io.*; import java.util.*;  /* A binary tree node has data, pointer to left child  and a pointer to right child */ class Node  {      int data;      Node left, right;           Node(int item)      {          data = item;          left = right = null;      }  }   class BinaryTree  {      Node root;       /* UTILITY FUNCTIONS */     // Function to fill hd in set.      void fillSet(Node root,Set<Integer> set,int hd)     {         if(root == null) return;         fillSet(root.left,set,hd - 1);         set.add(hd);         fillSet(root.right,set,hd + 1);     }       int verticalWidth(Node root)     {         Set<Integer> set = new HashSet<Integer>();                   // Third parameter is horizontal distance          fillSet(root,set,0);         return set.size();     }          /* Driver program to test above functions */     public static void main(String args[])      {          BinaryTree tree = new BinaryTree();                   /*          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);          System.out.println(tree.verticalWidth(tree.root));              }  }   /* This code is contributed by Ashok Borra */ 
Python3
# Python code to find vertical  # width of a binary tree  class Node:     def __init__(self, data):         self.data = data         self.left = self.right = None  # Function to fill hd in set.  def fillSet(root, s, hd):     if (not root):         return      fillSet(root.left, s, hd - 1)      s.add(hd)     fillSet(root.right, s, hd + 1)  def verticalWidth(root):     s = set()      # Third parameter is horizontal      # distance      fillSet(root, s, 0)       return len(s)  if __name__ == '__main__':      # Creating the above tree      root = Node(1)      root.left = Node(2)      root.right = Node(3)      root.left.left = Node(4)      root.left.right = Node(5)      root.right.left = Node(6)      root.right.right = Node(7)      root.right.left.right = Node(8)      root.right.right.right = Node(9)       print(verticalWidth(root))  # This code is contributed by PranchalK 
C#
// C# code to find the vertical width  // of a binary tree using System; using System.Collections.Generic;  /* A binary tree node has data,  pointer to left child and a  pointer to right child */ public class Node  {      public int data;      public Node left, right;           public Node(int item)      {          data = item;          left = right = null;      }  }   public class BinaryTree  {      Node root;       /* UTILITY FUNCTIONS */     // Function to fill hd in set.      void fillSet(Node root, HashSet<int> set, int hd)     {         if(root == null) return;         fillSet(root.left, set, hd - 1);         set.Add(hd);         fillSet(root.right, set, hd + 1);     }      int verticalWidth(Node root)     {         HashSet<int> set = new HashSet<int>();                   // Third parameter is horizontal distance          fillSet(root,set, 0);         return set.Count;     }          // Driver Code     public static void Main(String []args)      {          BinaryTree tree = new BinaryTree();                   /*          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);          Console.WriteLine(tree.verticalWidth(tree.root));              }  }  // This code is contributed by PrinciRaj1992  
JavaScript
<script>  // Javascript code to find the vertical  // width of a binary tree  /* A binary tree node has data,  pointer to left child and a  pointer to right child */ class Node  {      constructor(item)     {         this.data = item;         this.left = null;         this.right = null;     } }   var root;   /* UTILITY FUNCTIONS */ // Function to fill hd in set.  function fillSet(root,set, hd) {     if (root == null)          return;              fillSet(root.left, set, hd - 1);     set.add(hd);     fillSet(root.right, set, hd + 1); }  function verticalWidth(root) {     var set = new Set();           // Third parameter is horizontal      // distance      fillSet(root,set, 0);     return set.size; }  // Driver Code /*  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);   document.write(verticalWidth(root));  // This code is contributed by rrrtnx  </script> 

Output
6

Time Complexity: O(n)
Auxiliary Space: O(n)


Next Article
Vertical width of Binary tree | Set 1

A

Aashish Chauhan
Improve
Article Tags :
  • Tree
  • DSA
  • Binary Tree
Practice Tags :
  • Tree

Similar Reads

  • 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 Traversal of a Binary Tree
    Given a Binary Tree, the task is to find its vertical traversal starting from the leftmost level to the rightmost level. If multiple nodes pass through a vertical line, they should be printed as they appear in the level order traversal of the tree. Examples: Input: Output: [[4], [2], [1, 5, 6], [3,
    10 min read
  • Vertical Sum in a given Binary Tree
    Given a Binary Tree, find the vertical sum of the nodes that are in the same vertical line. Input: Output: 4 2 12 11 7 9Explanation: The below image shows the horizontal distances used to print vertical traversal starting from the leftmost level to the rightmost level. Table of Content Using map - O
    15 min read
  • 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
  • Validate the Binary Tree Nodes
    Given N nodes numbered from 0 to n-1, also given the E number of directed edges, determine whether the given nodes all together form a single binary tree or not. Examples: Input: N = 4, edges[][] = [[0 1], [0 2], [2 3]] Output: trueExplanation: Form a single binary tree with a unique root node. Inpu
    7 min read
  • Sum of all vertical levels of a Binary Tree
    Given a binary tree consisting of either 1 or 0 as its node values, the task is to find the sum of all vertical levels of the Binary Tree, considering each value to be a binary representation. Examples: Input: 1 / \ 1 0 / \ / \ 1 0 1 0Output: 7Explanation: Taking vertical levels from left to right:F
    10 min read
  • Vertical Traversal of a Binary Tree using BFS
    Given a Binary Tree, the task is to find its vertical traversal starting from the leftmost level to the rightmost level. Note that if multiple nodes at same level pass through a vertical line, they should be printed as they appear in the level order traversal of the tree. Examples: Input: Output: [[
    9 min read
  • Vertical Sum in Binary Tree (Space Optimized)
    Given a Binary Tree, find the vertical sum of the nodes that are in the same vertical line. Input: Output: 4 2 12 11 7 9Explanation: The below image shows the horizontal distances used to print vertical traversal starting from the leftmost level to the rightmost level. Approach: We have discussed Ha
    10 min read
  • Vertical Zig-Zag traversal of a Tree
    Given a Binary Tree, the task is to print the elements in the Vertical Zig-Zag traversal order. Vertical Zig-Zag traversal of a tree is defined as: Print the elements of the first level in the order from right to left, if there are no elements left then skip to the next level.Print the elements of t
    15 min read
  • Left View of a Binary Tree
    Given a Binary Tree, the task is to print the left view of the Binary Tree. The left view of a Binary Tree is a set of leftmost nodes for every level. Examples: Input: root[] = [1, 2, 3, 4, 5, N, N]Output: [1, 2, 4]Explanation: From the left side of the tree, only the nodes 1, 2, and 4 are visible.
    11 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences