Advertisement
urmisaha

Bottom-view of a binary tree

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