Advertisement
urmisaha

Right-view of a binary tree

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