Vertical Traversal of Binary Tree | Practice | GeeksforGeeks

Given a Binary Tree, find the vertical traversal of it starting from the leftmost level to the rightmost level.
If there are multiple nodes passing through a vertical line, then they should be printed as they appear in level order traversal of the tree.
Example 1:
Input:
           1
         /   \
       2       3
     /   \   /   \
   4      5 6      7
              \      \
               8      9           
Output: 
4 2 1 5 6 3 8 7 9 
Explanation:


Example 2:
Input:
       1
    /    \
   2       3
 /    \      \
4      5      6
Output: 4 2 1 5 3 6

Your Task:
You don't need to read input or print anything. Your task is to complete the function verticalOrder() which takes the root node as input parameter and returns an array containing the vertical order traversal of the tree from the leftmost to the rightmost level. If 2 nodes lie in the same vertical level, they should be printed in the order they appear in the level order traversal of the tree.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(N)
Constraints:
1 <= Number of nodes <= 3*104
0
tirtha19025682 days ago
class Solution
{
   static class pair{
       int dist;
       Node node;
       pair(int dist,Node node){
           this.dist = dist;
           this.node = node;
       }
   }
   
   static ArrayList <Integer> verticalOrder(Node root)
   {
       if(root == null) return null;
       ArrayList<Integer>ans = new ArrayList<>();
       Queue<pair>q = new LinkedList<>();
       Map<Integer,ArrayList<Integer>> map = new TreeMap<>();
       q.add(new pair(0,root));
       while(!q.isEmpty()){
           pair curr = q.poll();
           
           if(map.containsKey(curr.dist)){
               map.get(curr.dist).add(curr.node.data);
           }else{
               ArrayList<Integer>temp = new ArrayList<>();
               temp.add(curr.node.data);
               map.put(curr.dist,temp);
           }
           
           if(curr.node.left != null){
               q.add(new pair(curr.dist-1,curr.node.left));
           }
           if(curr.node.right != null){
               q.add(new pair(curr.dist+1,curr.node.right));
           }
       }
       
       for(Map.Entry<Integer,ArrayList<Integer>>m:map.entrySet()){
           for(int i=0;i<m.getValue().size();i++){
               ans.add(m.getValue().get(i));
           }
       }
       
       
       
       return ans;
   }
}
0
akashkhurana282 days ago
JAVA SOLUTION
 static class Pair {           Node node;           int hd;
           Pair(Node n, int h) {               node = n;               hd = h;           }       }       static ArrayList<Integer> verticalOrder(Node root) {              ArrayList<Integer>ans=new ArrayList<>();               if(root==null)               return ans;           Queue<Pair>q=new LinkedList<>();           Map<Integer,ArrayList<Integer>>mp= new TreeMap<>();           q.add(new Pair(root,0));           while(!q.isEmpty()){               Pair p=q.poll();               Node curr= p.node;               int hd=p.hd;               if(mp.containsKey(hd)){                   mp.get(hd).add(curr.data);               }               else{                   ArrayList<Integer>al= new ArrayList<>();                   al.add(curr.data);                   mp.put(hd,al);               }               if(curr.left!=null) q.add(new Pair(curr.left,hd-1));               if(curr.right!=null) q.add(new Pair(curr.right,hd+1));           }        for(Map.Entry<Integer,ArrayList<Integer>>e:mp.entrySet()){         ans.addAll(e.getValue());     }     return ans;  }} 
0
akshu199bhardwaj1 week ago
What is the problem with this code?
  public:   //Function to find the vertical order traversal of Binary Tree.   void helper(Node* root, int hd, map<int,vector<int>> &m){       if(!root) return;       m[hd].push_back(root->data);       helper(root->left,hd-1,m);       helper(root->right,hd+1,m);   }   vector<int> verticalOrder(Node *root)   {       vector<int> ans;       map<int,vector<int>> m;       helper(root,0,m);       for(auto e: m){           for(int i=0; i<e.second.size(); i++)           ans.push_back(e.second[i]);       }       return ans;   }
0
saicharanthammi2 weeks ago
vector<int> verticalOrder(Node *root)   {      map<int,vector<int>>mp;      pair<Node*,int>p;p.first=root;      p.second=0;vector<int>ans;      queue<pair<Node*,int>> q;      q.push(p);      while(!q.empty())      {          p=q.front();          mp[p.second].push_back(p.first->data);          if(p.first->left!=NULL) {q.push(make_pair(p.first->left,p.second-1)); }          if(p.first->right!=NULL){ q.push(make_pair(p.first->right,p.second+1));}          q.pop();      }      for(auto it: mp)            for(auto iter : it.second) ans.push_back(iter);
      return ans;   }
0
aishwaryadwani97992 weeks ago
class Solution{   //Function to find the vertical order traversal of Binary Tree.   static class Pair   {       Node node;       int horizontalDistance;       Pair(Node node,int horizontalDistance)       {           this.node=node;           this.horizontalDistance=horizontalDistance;       }   }   static ArrayList <Integer> verticalOrder(Node root)   {       Queue<Pair> bag = new LinkedList<>();       Pair pair = new Pair(root,0);       bag.add(pair);              Map<Integer,ArrayList<Integer>> mp = new HashMap<>();       int minimumHD = Integer.MAX_VALUE;       int maximumHD = Integer.MIN_VALUE;              while(!bag.isEmpty())       {           pair = bag.poll();           int key = pair.horizontalDistance;           int value = pair.node.data;                      if(mp.containsKey(key))           {               ArrayList<Integer> valueList = mp.get(key);               valueList.add(value);               mp.put(key,valueList);           }              else           {               ArrayList<Integer> valueList = new ArrayList<>();               valueList.add(value);               mp.put(key,valueList);           }                      if(pair.node.left!=null)           {               Pair leftPair = new Pair(pair.node.left,key-1);               bag.add(leftPair);           }           if(pair.node.right!=null)           {               Pair rightPair = new Pair(pair.node.right,key+1);               bag.add(rightPair);           }                      minimumHD = Math.min(minimumHD,key);           maximumHD = Math.max(maximumHD,key);       }              ArrayList<Integer> result = new ArrayList<>();              for(int i=0;i<mp.size();i++)       {           ArrayList<Integer> values = mp.get(minimumHD);           for(Integer value : values) result.add(value);           minimumHD += 1;       }              return result;   }}
0
aishwaryadwani9799
This comment was deleted.
+3
yoginpcs202 weeks ago
vector<int> verticalOrder(Node *root)
    {
        //Your code here
        queue<pair<Node*,int>> q;
        map<int,vector<int>>mp;
        q.push(make_pair(root,0));
        while(!q.empty())
        {
            auto p=q.front();
            Node* curr=p.first;
            int hd=p.second;
            mp[hd].push_back(curr->data);
            q.pop();
            if(curr->left!=NULL)
            q.push(make_pair(curr->left,hd-1));
            if(curr->right!=NULL)
            q.push(make_pair(curr->right,hd+1));
        }
        vector<int> ans;
        for(auto i:mp)
        {
            for(auto j:i.second)
            {
                ans.push_back(j);
            }
        }
        return ans;
        
    }
0
moaslam8263 weeks ago
c++ easy code
 vector<int> verticalOrder(Node *root)
    {
        map<int,vector<int>> um;
        vector<int> v;
         queue<pair<Node*,int>> q;
         q.push({root,0});
         while(!q.empty()){
             Node* temp=q.front().first;
             int h=q.front().second;
             um[q.front().second].push_back(temp->data);
             q.pop();
             if(temp->left) q.push(make_pair(temp->left,h-1));
             if(temp->right) q.push(make_pair(temp->right,h+1));
         }
         for(auto &it: um){
             for(auto &el : it.second) v.push_back(el);
         }
        return v;
    }
+1
parasnirban90503 weeks ago
vector<int> verticalOrder(Node *root)   {       vector<int> v;       if(root==nullptr)       return v;       map<int,vector<int>> mp;       queue<pair<Node*,int>> q;       q.push({root,0});       while(!q.empty()){           vector<int> temp;           auto it=q.front();           q.pop();           Node* node=it.first;           int hd=it.second;           mp[hd].push_back(node->data);           if(node->left!=nullptr){               q.push({node->left,hd-1});           }           if(node->right!=nullptr){               q.push({node->right,hd+1});           }       }       for(auto it: mp){           for(auto j : it.second){               v.push_back(j);           }       }       return v;   }
0
sachinsinghss193 weeks ago
Python solution1. Create vertical levels for left and right sides of the tree
2. Iterate through the levels in sorted order
def verticalOrder(self, root):        #Your code here       levels = {}       q = [(root, 0)]       while q:           nd, ind = q.pop(0)              if ind not in levels:               levels[ind] = [nd.data]           else:               levels[ind].append(nd.data)           if nd.left:               q.append((nd.left, ind + 1))              if nd.right:               q.append((nd.right, ind - 1))                      op = []       for v in sorted(levels, reverse=True):           op += levels[v]              return op
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.