Top View of Binary Tree | Practice | GeeksforGeeks

Given below is a binary tree. The task is to print the top view of binary tree. Top view of a binary tree is the set of nodes visible when the tree is viewed from the top. For the given below tree
       1
    /     \
   2       3
  /  \    /   \
4    5  6   7
Top view will be: 4 2 1 3 7
Note: Return nodes from leftmost node to rightmost node.
Example 1:
Input:
      1
   /    \
  2      3
Output: 2 1 3

Example 2:
Input:
       10
    /      \
  20        30
 /   \    /    \
40   60  90    100
Output: 40 20 10 30 100

Your Task:
Since this is a function problem. You don't have to take input. Just complete the function topView() that takes root node as parameter and returns a list of nodes visible from the top view from left to right.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(N).
Constraints:
1 ≤ N ≤ 105
1 ≤ Node Data ≤ 105
 
Note:The Input/Ouput format and Example given are used for 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 stdin/console. The task is to complete the function specified, and not to write the full code.
0
rmn51243 days ago
vector<int> topView(Node *root)
    {
        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;
            
            if(m.find(x)==m.end())
            m[x]=node->data; // only insert if its first vertical i.e only diff from bottom view
            
            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 value
        }
        return v;
    }

+1
jeffprivate03136 days ago
Runs in 0.05, simple solution.
global: vector<pair<int,int>> a;
    void tr(Node * n, int level,int pos) {       if(n==NULL){           return;       }       if(a[pos].first==0){//initialize            a[pos]=make_pair(n->data, level);//switch       }else if(a[pos].first!=0){           if(level<a[pos].second){//higher, will cover the old node               a[pos]=make_pair(n->data,level);           }       }       tr(n->left, level+1, pos-1);//go to left node, level+1,position-1       tr(n->right, level+1, pos+1);//same   }   vector<int> topView(Node *root)   {          a.clear();//clear since global vector       for(int g=0;g<20002;g++){           a.push_back({0,20000});//value and level, we initialize since we note all data are 1≤data≤10000.       }       tr(root,0,10000);//traverse with position 10000 since we don't want to die from negative numbers        vector<int>final={};//just solution vector       for(int i=0;i<20002;i++){//look from left to right           if(a[i].first!=0){//if initialized               final.push_back(a[i].first);//include           }       }       return final;   }
 
0
jainmuskan5651 week ago
vector<int> topView(Node *root)   {       // we are going to use queue and map       // line traversal where root is zero, left is -1 and right is +1       // base case       vector<int> res;       if(root==NULL){           return res;       }       // first element of each line level is appended in map       // queue is used to traverse all the nodes       map<int,int> linemap;       queue<pair<Node*,int>> q;       q.push({root,0});       linemap[0]=root->data;       while(!q.empty()){           auto it= q.front();           q.pop();           int line= it.second;           Node * n= it.first;           if(linemap.find(line)==linemap.end()){               linemap[line]= n->data;           }                      // now traverse the left and right nodes           if(n->left){               q.push({n->left, line-1});           }           if(n->right){               q.push({n->right, line+1});           }       }       for(auto i:linemap){           res.push_back(i.second);       }       return res;   }
0
rohanmeher1641 week ago
//Java solution
 
 
class Solution{      static ArrayList<Integer> topView(Node root)   {     ArrayList<Integer> list=new ArrayList<Integer>();       if(root==null) return list;       Queue<Pair> q=new LinkedList<Pair>();        Map<Integer,Integer> m= new TreeMap<Integer,Integer>();       q.add(new Pair(0,root));       m.put(0,root.data);              while(!q.isEmpty())       {              Pair c=q.poll();            if(!m.containsKey(c.hd))  m.put(c.hd,c.node.data);               if(c.node.left!=null)               {                    q.add(new Pair(c.hd-1,c.node.left));                                 }                if(c.node.right!=null)                 {                      q.add(new Pair(c.hd+1,c.node.right));                }           }            for(Map.Entry<Integer,Integer> e:m.entrySet())              list.add(e.getValue());                       return list;       }     }       class Pair   {       int hd;       Node node;       public Pair(int h,Node n)       {           hd=h;           node=n;       }   }   
+1
devangrao251 week ago
C++ || Easy || O(n) 
 
vector<int> topView(Node *root)   {
       //vertical order traversal code with modification       unordered_map<int, int> mp;       queue<pair<Node*, int>> q;       q.push({root, 0});              int mn = 0, mx = 0;       while(!q.empty())  //simple level order traversal       {           pair<Node*, int> p = q.front();           q.pop();                      int hd = p.second;           Node* t = p.first;           
           //we store only first node of each Horizontal dist            if(mp.count(hd) == 0)                 mp[hd] = (t->data);                      if(t->left)   //for left child=> hd is hd(root) - 1;              q.push({t->left, hd - 1});           if(t->right)              q.push({t->right, hd + 1});                      mn = min(mn, hd);           mx = max(mx, hd);          }                                    vector<int> ans;       for(int i = mn; i <= mx; i++)  //for hd to be in order       {           ans.push_back(mp[i]);   //directly print as we stored only first node of each hd       }     return ans;   }
0
tirtha19025681 week ago

class Solution
{
   static ArrayList<Integer> topView(Node root)
   {
       if(root == null) return null;
       ArrayList<Integer>ans = new ArrayList<>();
       topView(root,ans);
       return ans;
       
   }
   
static class pair{
 int dist;
 Node node;
 pair(int dist,Node node){
  this.node = node;
  this.dist = dist;
 }
}

static void topView(Node root,ArrayList<Integer>ans) {
    if(root == null) return;
Map<Integer,Integer>map = new TreeMap<>();
Queue<pair>q = new LinkedList<>();
q.add(new pair(0,root));

while(!q.isEmpty()) {
 pair curr = q.poll();
 map.putIfAbsent(curr.dist, curr.node.data);
 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, Integer>m:map.entrySet()) {
 ans.add(m.getValue());
}
 
}

   
}
+2
badgujarsachin832 weeks ago
vector<int> topView(Node *root)
    {
       vector<int> v;
       if(root==NULL){
           return v;
       }
       queue<pair<Node*,int>> q;
       int dis=0;
       q.push({root,0});
       map<int,int> mp;
       while(!q.empty()){
           int size=q.size();
           for(int i=0;i<size;i++){
               Node* temp=q.front().first;
               int dis=q.front().second;
               q.pop();

               if(mp.find(dis)==mp.end()){
                   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;
    }

+1
kumkumjain6162 weeks ago
class Pair{
    Node node;
    int hd;
    
    public Pair(Node node, int hd){
        this.node = node;
        this.hd = hd;
    }
}
class Solution
{
    static ArrayList<Integer> topView(Node root)
    {
        ArrayList<Integer> ans = new ArrayList<>();
        TreeMap<Integer,Integer> map = new TreeMap<>();
        
        Queue<Pair> q = new LinkedList<>();
        
        q.add(new Pair(root, 0));
        
        while(! q.isEmpty()){
            Pair pair = q.poll();
            
            Node node = pair.node;
            int hd = pair.hd;
            
            if(map.get(hd) == null){
                map.put(hd, node.data);
            }
            
            if(node.left != null)
                q.offer(new Pair(node.left, hd-1));
        
        if(node.right != null){
            q.offer(new Pair(node.right, hd+1));
        }
    }
    
    for(Map.Entry<Integer, Integer> entry : map.entrySet()){
        ans.add(entry.getValue());
    }
    return ans;
    }
}
0
amit092 weeks ago
class Solution
{
    map<int,pair<int,int>> myMap; //Map<width,pair<level,data>>
    public:
    //Function to return a list of nodes visible from the top view 
    //from left to right in Binary Tree.
    void topView(Node* root, int width, int level)
    {
        if(!root) return;
        auto iter = myMap.find(width) ;
        if(iter == myMap.end() ){
            myMap[width] = {level,root->data};
            //cout<<width<< "  "<<root->data<<endl;
        } else {
            if(iter->second.first > level){
                myMap[width] = {level,root->data};
            }
        }
        
        topView(root->left, width-1, level+1);
        topView(root->right, width+1, level+1);
    }
    vector<int> topView(Node *root)
    {
        vector<int> retVec;
        topView(root, 0, 1);
        
        for(auto it : myMap){
            retVec.push_back(it.second.second);
        }
        
        return retVec;
    }

};

0
shilsoumyadip2 weeks ago
vector<int> topView(Node *root)   {       //Your code  vector <int> bottomView(Node *root) {       // Your Code Here       map<int ,int>m;       queue<pair <Node*, int>>q;       vector<int>ans;       if(!root)       return ans;       q.push({root,0});       while(!q.empty())       {           Node* t = q.front().first;           int h = q.front().second;           q.pop();                      if(!m[h])              m[h] = t-> data;              if(t->left) q.push({t->left ,h-1});              if(t-> right)  q.push({ t-> right , h+1});           }   for(auto x:m)   ans.push_back(x.second); return ans;      }
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.