Vertical Width of a Binary Tree | Practice | GeeksforGeeks

Given a Binary Tree of N nodes. Find the vertical width of the tree.

Example 1:
Input:
          1
       /    \
      2      3
     / \    / \
    4   5  6   7
            \   \
             8   9
Output: 6
Explanation: The width of a binary tree is
the number of vertical paths in that tree.



The above tree contains 6 vertical lines.
 
Example 2:
Input:
      1
    /  \
   2    3
Output: 3

 
Your Task:
You don't have to read input or print anything. Your task is to complete the function verticalWidth() which takes root as the only parameter, and returns the vertical width of the binary tree.
 
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the Tree).
 
Constraints:
1 <= Number of nodes <= 105
0
prasad119042891 week ago
Simple approach in Java
 
public static int[] helper(Node root){       int[] res = new int[2];       if(root == null){           return res;       }       int[] leftres = helper(root.left);       int[] rightres = helper(root.right);       res[0] = Math.max(leftres[0]+1,rightres[0]-1);       res[0] = Math.max(res[0],0);       res[1] = Math.max(leftres[1]-1,rightres[1]+1);       res[1] = Math.max(res[1],0);       return res;   }   //Function to find the vertical width of a Binary Tree.   public static int verticalWidth(Node root){    // code here.    if(root == null){        return 0;    }    int[] res = helper(root);    return res[0]+res[1]-1;}
0
amankumar2783 weeks ago
Very EASY JAVA SOLUTION:
Without use of HashMap:
NOTE: I removed STATIC from both function:
 
class Tree{  int max=0;  int min=0;   public void resl(Node root,int index){       if(index>max)           max=index;       if(index<min)           min=index;       if(root.left!=null)           resl(root.left,index-1);       if(root.right!=null)           resl(root.right,index+1);   }   //Function to find the vertical width of a Binary Tree.   public int verticalWidth(Node root){    // code here.    if(root==null){        return 0;    }    resl(root,0);    return max-min+1;}}
0
rohanyt744 weeks ago
void inorder(Node*root,int h, unordered_set<int>&st){    if(!root)return;    else{        inorder(root->left,h-1,st);        st.insert(h);                inorder(root->right,h+1,st);    }}int verticalWidth(Node* root){   // Code here   unordered_set<int>st;    inorder(root,0,st);    return st.size();} 
+2
tbomble62921 month ago
unordered_set<int>st;
void inorder(Node *root, int hd)
{
   if(root != NULL)
   {
       inorder(root->left, hd-1);
       st.insert(hd);
       inorder(root->right, hd+1);
   }
}

int verticalWidth(Node* root)
{
   st.clear();
   inorder(root, 0);
   return st.size();
}
0
amanavengeraman1 month ago
public static int verticalWidth(Node root){    if(root == null){        return 0;    }    HashMap<Integer, Integer> hm = new HashMap<>();    lvl(root, 0, hm);       return hm.size();}static void lvl(Node root, int dis, HashMap<Integer, Integer> hm){    if(root == null){        return;    }        if(!hm.containsKey(dis)){        hm.put(dis,root.data);     }    lvl(root.left, dis-1, hm);    lvl(root.right, dis+1, hm);    return;}
0
forcer2 months ago
 map<int,int>m;
    if(!root) return 0;
    queue<pair<Node*,int>>q;
    q.push({root,0});
    while(!q.empty())
    {
        Node *t=q.front().first;
        int val=q.front().second;
        q.pop();
        m[val]++;
        if(t->left) q.push({t->left,val-1});
        if(t->right) q.push({t->right,val+1});
    }
    return m.size();
+5
gurjotsingh21003Premium2 months ago
EASY C++ solution
void width(Node* root,int& lmost,int& rmost,int level)
{
   if(root==NULL)return;
   
   width(root->left,lmost,rmost,level-1);
   lmost=min(lmost,level);
   width(root->right,lmost,rmost,level+1);
   rmost=max(rmost,level);
}
int verticalWidth(Node* root)
{
   // Code here
   if(root==NULL)return 0;
   int lmost=INT_MAX;
   int rmost=INT_MIN;
   int level=0;
   width(root,lmost,rmost,level);
   return (rmost-lmost+1);
}
+2
harshitraj7122 months ago
Nasa walon se jyaada toh tree ke sawaal khatarnaak hain
0
shubhamkavia1998
This comment was deleted.
0
ankitgupta502 months ago
// BFS Approach
class Tree{      public static class Pair{       Node root;       int level;       Pair(Node root, int level){           this.root = root;           this.level = level;       }   }   //Function to find the vertical width of a Binary Tree.   public static int verticalWidth(Node root){    if(root==null)        return 0;    Queue<Pair> q = new LinkedList<>();    q.add(new Pair(root,1));    int min = Integer.MAX_VALUE;    int max = Integer.MIN_VALUE;    while(!q.isEmpty()){        Pair temp = q.remove();        min = Math.min(min,temp.level);        max = Math.max(max,temp.level);        if(temp.root.left!=null){            q.add(new Pair(temp.root.left,temp.level-1));        }        if(temp.root.right!=null){            q.add(new Pair(temp.root.right,temp.level+1));        }    }    return max-min+1;}}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.