Bottom View of Binary Tree | Practice | GeeksforGeeks

Given a binary tree, print the bottom view from left to right.
A node is included in bottom view if it can be seen when we look at the tree from bottom.
                      20
                    /    \
                  8       22
                /   \        \
              5      3       25
                    /   \      
                  10    14
For the above tree, the bottom view is 5 10 3 14 25.
If there are multiple bottom-most nodes for a horizontal distance from root, then print the later one in level traversal. For example, in the below diagram, 3 and 4 are both the bottommost nodes at horizontal distance 0, we need to print 4.
                      20
                    /    \
                  8       22
                /   \     /   \
              5      3 4     25
                     /    \      
                 10       14
For the above tree the output should be 5 10 4 14 25.
 
Example 1:
Input:
       1
     /   \
    3     2
Output: 3 1 2
Explanation:
First case represents a tree with 3 nodes
and 2 edges where root is 1, left child of
1 is 3 and right child of 1 is 2.

Thus nodes of the binary tree will be
printed as such 3 1 2.
Example 2:
Input:
         10
       /    \
      20    30
     /  \
    40   60
Output: 40 20 60 30

Your Task:
This is a functional problem, you don't need to care about input, just complete the function bottomView() which takes the root node of the tree as input and returns an array containing the bottom view of the given tree.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 <= Number of nodes <= 105
1 <= Data of a node <= 105

Note: The Input/Output format and Example given are used for the system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from the stdin/console. The task is to complete the function specified, and not to write the full code.
0
archit232001 week ago
JAVA Solution Based on Striver's approach:-
 
class ds{
    Node node;
    int verticalIndex;
    ds(Node node,int verticalIndex){
        this.node=node;
        this.verticalIndex=verticalIndex;
    }
}
class Solution
{
    //Function to return a list containing the bottom view of the given tree.
    public ArrayList <Integer> bottomView(Node root)
    {
        // Code here
        Queue<ds> q=new LinkedList<>();
        ArrayList<Integer> ans=new ArrayList<>();
        Map<Integer,Integer> m=new TreeMap<>();
        q.offer(new ds(root,0));
        while(q.isEmpty()==false){
            ds d=q.poll();
            if(m.containsKey(d.verticalIndex)==false){
                m.put(d.verticalIndex,d.node.data);
            }
            m.put(d.verticalIndex,d.node.data);
            if(d.node.left!=null) q.offer(new ds(d.node.left,d.verticalIndex-1));
            if(d.node.right!=null) q.offer(new ds(d.node.right,d.verticalIndex+1));
        }
        for(Integer i:m.values()){
            ans.add(i);
        }
        return ans;
    }
}
0
rmn51241 week ago
class Solution {
  public:
    vector <int> bottomView(Node *root) {
        // Your Code Here
        queue<pair<Node*,int>>q;//node,level
        map<int,int>m; //level,verticle
        q.push({root,0});
        while(!q.empty()){
            auto f=q.front();
            q.pop();
            auto node=f.first;
            int x=f.second;
            m[x]=node->data; //rightmost value i.e. it will replace with the rightmost node in the same level
            
            if(node->left)  q.push({node->left,x-1});
            if(node->right)
                q.push({node->right,x+1});
        }
        vector<int>v;
        for(auto i:m){
            v.push_back(i.second); // insert calue
        }
        return v;
    }
};
0
jainmuskan5652 weeks ago
    vector <int> bottomView(Node *root) {
       vector<int> res;
       if(!root){
           return res;
       }
       // using the line view concept and maps
       map<int,int> mp;
       // considereing the root as 0
       mp[0]= root->data;
       // queue to traverse all the nodes
       queue<pair<Node *,int>> q;
       q.push({root,0});
       while(!q.empty()){
           auto curr= q.front();
           Node * node= curr.first;
           int line= curr.second;
           q.pop();
           mp[line]= node->data;
           if(node->left){
               q.push({node->left, line-1});
           }
           if(node->right){
               q.push({node->right,line+1});
           }
       }
       for(auto x:mp){
           res.push_back(x.second);
       }
       return res;
   }
0
saicharanthammi2 weeks ago
    vector <int> bottomView(Node *root) {      map<int,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]=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 iter:mp)     ans.push_back(iter.second);
      return ans;   }
0
vivekkumar483033 weeks ago
// 0(N) solution
int mn=INT_MAX;       unordered_map<int,int>m;       vector<int>ans;       queue<pair<Node*,int>>q;       q.push({root,0});              while(!q.empty())       {           auto it=q.front();           q.pop();                      int i1=it.second;           auto i2=it.first;                      m[i1]=i2->data;           mn=min(i1,mn);                      if(i2->left)q.push({i2->left,i1-1});           if(i2->right)q.push({i2->right,i1+1});       }       while(m.find(mn)!=m.end())       {           ans.push_back(m[mn]);           mn++;       }       return ans;
0
udaytyagi01234 weeks ago
class Solution { public:   vector <int> bottomView(Node *root)    {       map<int,Node*>m;       queue<pair<Node*,int>>q;       vector<int>ans;       if(root==NULL)       {           return ans;       }       q.push({root,0});       m[0]=root;       while(!q.empty())       {           Node*temp=q.front().first;           int line =q.front().second;           q.pop();           if(temp->left)           {               q.push({temp->left,line-1});               m[line-1]=temp->left;           }           if(temp->right)           {               q.push({temp->right,line+1});               m[line+1]=temp->right;           }       }       for(auto p:m)       {           ans.push_back(p.second->data);       }       return ans;   }};
0
moaslam8264 weeks ago
C++ easy code
 vector <int> bottomView(Node *root) {
        map<int,int> um;
        queue<pair<Node*,int>> q;
        q.push({root,0});
        while(!q.empty()){
            Node *temp=q.front().first;
            int h=q.front().second;
            um[h]=temp->data;
            q.pop();
            if(temp->left) q.push({temp->left,h-1});
            if(temp->right) q.push({temp->right,h+1});
        }
        vector<int> v;
        for(auto &it: um){
            v.push_back(it.second);
        }
        return v;  
    }
0
kkumar2k1001 month ago
vector <int> bottomView(Node *root) {
        // Your Code Here
        vector<int> v;
        if(!root){
            return v;
        }
        queue<pair<Node*,int>> q;
        map<int,int> mp;
        q.push({root,0});
        while(!q.empty()){
            Node* temp=q.front().first;
            int dis=q.front().second;
            q.pop();
            mp[dis]=temp->data;
            if(temp->left){
                q.push({temp->left,dis-1});
            }
            if(temp->right){
                q.push({temp->right,dis+1});
            }
        }
        for(auto it:mp){
            v.push_back(it.second);
        }
        return v;
    }
0
19042191 month ago
    queue<pair<Node*, int>>q;       q.push({root, 0});       // map<int, vector<int>>mp;       map<int , int>mp;       vector<int>res;       while(!q.empty()){           int sz = q.size();           for(int i=0; i<sz; i++){               auto p = q.front();               q.pop();               Node* curr = p.first;               // if(mp.find(p.second)==mp.end()){               mp[p.second]=(curr -> data);               // }               if(curr -> left){                   q.push({curr -> left, p.second - 1});               }               if(curr -> right){                   q.push({curr -> right, p.second + 1});               }           }       }       for(auto i:mp){           // for(auto j:i.second)           // res.push_back(j);           res.push_back(i.second);       }       return res;   }
+2
adarshgupta4011 month ago
Easy Java Soln using Level Order
class Solution
{
    //Function to return a list containing the bottom view of the given tree.
    // using BFS, Level order , a queue, and map .
    
    public ArrayList <Integer> bottomView(Node root)
    {
        // Code here
        ArrayList<Integer> res = new ArrayList<>();
        Map<Integer, Integer> map = new TreeMap<>();
        Queue<pair> q = new LinkedList<>();
        
        if(root == null ) return res;
        
        q.offer(new pair(0, root));
        while( !q.isEmpty()){
            pair next = q.remove();
            int column = next.key;
            Node temp = next.node;
            
            map.put(column, temp.data); // either update node value or put new.
            
            if(temp.left != null) q.add(new pair(column-1, temp.left) );
            if(temp.right != null) q.add(new pair(column+1, temp.right) );
        }
        
        for(Map.Entry<Integer, Integer> entry : map.entrySet() ){
            res.add(entry.getValue() );
        }
        
        return res;
    }
}
class pair{
        int key;
        Node node;
        pair(int k, Node n){
            key = k;  node = n;
        }
}

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.