Advertisement
urmisaha

Top-view of a binary tree

Nov 15th, 2019
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.92 KB | None | 0 0
  1. using namespace std;
  2.  
  3. /* A binary tree node has data, pointer to left child
  4.    and a pointer to right child */
  5. struct Node
  6. {
  7.     int data;
  8.     struct Node* left;
  9.     struct Node* right;
  10.  
  11.     Node(int x){
  12.         data = x;
  13.         left = right = NULL;
  14.     }
  15. };
  16.  
  17. void topView(struct Node *root);
  18.  
  19. /* Driver program to test size function*/
  20. int main()
  21. {
  22.   int t;
  23.   struct Node *child;
  24.   cin >> t;
  25.  
  26.   while (t--)
  27.   {
  28.      map<int, Node*> m;
  29.      int n;
  30.      cin >> n;
  31.      struct Node *root = NULL;
  32.      while (n--)
  33.      {
  34.         Node *parent;
  35.         char lr;
  36.         int n1, n2;
  37.         scanf("%d %d %c", &n1, &n2, &lr);
  38.         if (m.find(n1) == m.end())
  39.         {
  40.            parent = new Node(n1);
  41.            m[n1] = parent;
  42.            if (root == NULL)
  43.              root = parent;
  44.         }
  45.         else
  46.            parent = m[n1];
  47.         child = new Node(n2);
  48.         if (lr == 'L')
  49.           parent->left = child;
  50.         else
  51.           parent->right = child;
  52.         m[n2]  = child;
  53.      }
  54.  
  55.      topView(root);
  56.      cout << endl;
  57.   }
  58.   return 0;
  59. }
  60.  
  61. /*This is a function problem.You only need to complete the function given below*/
  62. //Structure of binary tree
  63. /*struct Node
  64. struct Node
  65. {
  66.     int data;
  67.     struct Node* left;
  68.     struct Node* right;
  69.    
  70.     Node(int x){
  71.         data = x;
  72.         left = right = NULL;
  73.     }
  74. };*/
  75. // function should print the topView of the binary tree
  76. void topView(struct Node *root)
  77. {
  78.     if(!root)
  79.         return;
  80.     map<int, int> m;
  81.     queue<pair<Node *, int> > q;
  82.     q.push({root, 0});
  83.     while(!q.empty()){
  84.         Node *n = q.front().first;
  85.         int l = q.front().second;
  86.         q.pop();
  87.         m.insert({l, n->data});
  88.         if(n->left)
  89.             q.push({n->left, l-1});
  90.         if(n->right)
  91.             q.push({n->right, l+1});
  92.     }
  93.     for(auto it=m.begin(); it!=m.end(); ++it)
  94.         cout<<(it->second)<<" ";
  95. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement