Guest User

Untitled

a guest
Feb 24th, 2020
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.82 KB | None | 0 0
  1. #include <iostream>
  2. #include <queue>
  3. #include <unordered_map>
  4. #include <algorithm>
  5. using namespace std;
  6. //Here I am making one additional field in node called height
  7. //which will store left and right ht of tree to the left ht becomes negative
  8. //form the root and right height becomes positive
  9.  
  10. class node{
  11.   public :
  12.     int data ;
  13.     node *left, *right;
  14.     int level;
  15.     node(int d){
  16.         data = d;
  17.         left = right = NULL;
  18.         level = 0;
  19.     }
  20.    
  21. };
  22.  
  23. node *build(){
  24.     int d;
  25.     cin>>d;
  26.     node* root = NULL;
  27.     if(d != -1){
  28.         root = new node(d);
  29.         queue<node*> q;
  30.         q.push(root);
  31.         while(!q.empty()){
  32.             node *f = q.front();
  33.             int d1, d2;
  34.             cin>>d1>>d2;
  35.             if(d1 != -1){
  36.                 f->left = new node(d1);
  37.                 f->left->level = f->level - 1;
  38.                 q.push(f->left);
  39.             }
  40.             if(d2 != -1){
  41.                 f->right = new node(d2);
  42.                 f->right->level = f->level + 1;
  43.                 q.push(f->right);
  44.             }
  45.         }
  46.     }
  47.     return root;
  48. }
  49.  
  50. int height(node* root){
  51.     if(root == NULL){
  52.         return 0;
  53.     }
  54.     int l = height(root->left);
  55.     int r = height(root->right);
  56.     return max(l, r) + 1;
  57.    
  58. }
  59.  
  60. void topView(node* root, unordered_map<int, int> &m){
  61.     if(m[root->level] != -1 || root == NULL)
  62.         return;
  63.     m[root->level] = root->data;
  64.     topView(root-> left, m);
  65.     topView(root-> right, m);
  66.    
  67. }
  68.  
  69. int main(){
  70.     node *root = build();
  71.     //creating unordered map storing tree information
  72.     unordered_map <int, int> m;
  73.     int limit = height(root);
  74.     for(int i = -limit; i <= limit ; i++)
  75.         m[i] = -1;
  76.     topView(root, m);
  77.     for(auto p : m){
  78.         cout<<p.second<<" ";
  79.     }
  80.     return 0;
  81. }
Add Comment
Please, Sign In to add comment