Advertisement
urmisaha

Left-view of a binary tree

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